what is the nullable integer and where can it be used?
A nullable integer is an integer that defaults to null instead of zero. It can also be set to null. It can be used anywhere you like. Look at the docs
The nullable integer int?
or Nullable<int>
is a value type in C# whose value can be null
or an integer value. It defaults to null
instead of 0
, and is useful for representing things like value not set
(or whatever you want it to represent).
Im assuming you mean int? x;
which is shorthand for Nullable<int> x;
This is a way of adding nulls to value types, and is useful in scenarios such as database processing where values can also be set to null. By default a nullable type contains null and you use HasValue to check if it has been given a value. You can assign values and otherwise use it like a normal value type.
A nullable integer can be used in a variety of ways. It can have a value or null. Like here:
int? myInt = null;
myInt = SomeFunctionThatReturnsANumberOrNull()
if (myInt != null) {
// Here we know that a value was returned from the function.
}
else {
// Here we know that no value was returned from the function.
}
Let's say you want to know the age of a person. It is located in the database IF the person has submitted his age.
int? age = GetPersonAge("Some person");
If, like most women, the person hasn't submitted his/her age then the database would contain null.
Then you check the value of age
:
if (age == null) {
// The person did not submit his/her age.
}
else {
// This is probably a man... ;)
}
int? year;
you could put them in your controller actions and if the URL didn't contain the year parameter year would be null, as opposed to defaulting it to 0 which might be a valid value for your application.
A nullable type will accept its value type, and an additional null value.Useful for databases and other data types containing elements that might not be assigned a value.