开发者

Nullable integer in .NET

开发者 https://www.devze.com 2022-12-28 19:12 出处:网络
what is the nullable开发者_运维百科 integer and where can it be used?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

what is the nullable开发者_运维百科 integer and where can it be used?


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).


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... ;)
}


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.


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.


Whenever you could not predict the result or output from the particular business logic, go with nullable types.

Default value type (Ex. Int) can not be null. It thorws out an error while try to assign null value. But the nullable types won't do that.

Thanks.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号