Pikachu620
Pikachu620

Reputation: 483

Nullable<T> Structure

I read Nullable Structure and understand most of it. But I don't know when and why people will use it.

Upvotes: 0

Views: 112

Answers (2)

LeopardSkinPillBoxHat
LeopardSkinPillBoxHat

Reputation: 29421

C# has the concept of reference types (classes) and value types (structs and built-in types such as int, bool, DateTime, etc.).

Reference types can have a null value, indicating that they haven't been assigned (or they have "no" value).

Value types didn't originally have a concept of a nullable value. They have a default value in some contexts (e.g. an int field in a class has a default value of 0). But they don't have the concept of "no" value.

Enter Nullable<T>.

Nullable<T> (or its shorthand notation of T?) indicates a value-type which may or may not have a value.

e.g.

int? foo = null; // No initial value
foo = 9; // Now it has a value
foo = null; // No value again

And there are methods to query whether the value exists, and retrieve it:

if (foo.HasValue)
{
    int actualValue = foo.Value;
}

One area where this is useful is when writing code to connect to databases. Numerical (integer) columns in many databases can be configured to be nullable. Without nullable types in C# itself, you'd need to jump through hoops to handle a null DB value in code (e.g. using a special sentinel value to represent a null DB value). Nullable types make this operate in a more seamless manner.

Upvotes: 5

Hossein Golshani
Hossein Golshani

Reputation: 1897

Usage of Nullable<T> is broad. For an example suppose that you have a query that returns the id of last post of specific user on blog:

int lastId = User.GetLastPostId();

If the user hasn't any post yet, the method returns null and causes an exception. the solution is using Nullable<int> instead of int to avoid error.

int? lastId = User.GetLastPostId();

In this case you can even check to be null or not:

if(lastId == null)
    // do something
else
    // do something

Something like above, suppose you want to use struct instead of class in your code. As far as the struct is ValueType, it can't accept null value and if you want to force the struct to accept null value, you should define it as Nullable.

Struct Person
{
    public string Name;
}

Person p = null; // Error
Person? p = null; // Correct

Upvotes: 2

Related Questions