0

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

4
  • 1
    This will be subjective and primarily opinion based and also too broad Commented Jun 6, 2018 at 1:40
  • But could you please point me to the right direction please!? Commented Jun 6, 2018 at 1:42
  • @Pikachu Please note that the visual-studio tag is for IDE questions. Commented Jun 6, 2018 at 1:57
  • 1
    Broad maybe, but I don't see how this is subjective or opinion based. Commented Jun 6, 2018 at 2:10

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.