Xulfee
Xulfee

Reputation: 986

Nullable integer in .NET

what is the nullable integer and where can it be used?

Upvotes: 11

Views: 18076

Answers (6)

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.

Upvotes: 0

SRA
SRA

Reputation: 1691

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.

Upvotes: 0

danswain
danswain

Reputation: 4177

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.

Upvotes: 0

Sani Huttunen
Sani Huttunen

Reputation: 24385

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

Upvotes: 8

James Westgate
James Westgate

Reputation: 11444

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.

Upvotes: 0

H&#229;vard S
H&#229;vard S

Reputation: 23876

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

Upvotes: 21

Related Questions