Understanding Nullable in C#

Let us try to understand Nullable types little deeper, by asking these questions what will happen when you,

  • Assign a Nullable type to Non Nullable type?
  • Assign a Nullable type value to Non Nullable type?
  • Access the method of Nullable Structure – GetValueOrDefault()

When you apply Nullable structure to value type, Nullable structure expose these property and methods to access the values.

  • HasValue – Property
  • Value – Property
  • GetValueOrDefault() – Method

Assign a Nullable type to Non Nullable types?

You cannot assign a Nullable type to a non Nullable type. Compiler will throw compile time error.

Code Example:

Error: CS0266  cannot implicitly convert type ‘int?’ to ‘int’. An explicit conversion exists (are you missing a cast?)

Assign a Nullable Structure’s Value (property) to Non Nullable type?

Consider the below code, now you won’t get any compile time error, but certainly you will get the run time error, compiler throws runtime exception when the particular line of code tries to assign Nullable value to a non Nullable type.

Code Example:

Error:  An unhandled exception of type ‘System.InvalidOperationException’ occurred in mscorlib.dll, Additional information: Nullable object must have a value.

So what is the solution for this problem, Nullable structure have a method called “GetValueOrDefault()” which used to get the default value. If the value is null, it will return the default value of the value type.

Code Example

0 comments… add one

Leave a Comment