Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable integer in .NET

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

like image 774
Xulfee Avatar asked Apr 29 '10 08:04

Xulfee


People also ask

What is nullable int in C#?

In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a special feature to assign a null value to a variable that is known as the Nullable type. The Nullable type allows you to assign a null value to a variable.

What is the default value of nullable int C#?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .

How do you handle nullable values in C#?

Empty(A constant for empty strings). This method will take a parameter that will be of System. String type. The method will return a Boolean value, like n case if the argument String type has null or empty string (“”), then it will return True value else it will return False value.

Can we have nullable structure in C#?

For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null . The Nullable<T> structure supports using only a value type as a nullable type because reference types are nullable by design. The Nullable class provides complementary support for the Nullable<T> structure.


2 Answers

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

like image 146
Håvard S Avatar answered Sep 18 '22 13:09

Håvard S


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... ;)
}
like image 30
Sani Singh Huttunen Avatar answered Sep 19 '22 13:09

Sani Singh Huttunen