find and solve || findandsolve.com
Please wait.....

Nullable reference types in C#

In the C# programming language, The Nullable reference types aren't new class types, but rather annotations on existing reference types. The compiler uses those annotations to help us find potential null reference errors in our code. There is no runtime difference between a non-nullable reference type and a nullable reference type.

In the c# programming language, The Nullable Types are useful to assign a null value to the value type variables. In c#, if you try to assign a null value to the value type variables, then you will get a compile-time error.


In the given example of assigning a null value to the value type variables in c#.

using System;
namespace FindAndSolve
{
    public class Program
    {
       public static void Main(string[] args)
       {
         int a = null;
         bool b = null;
         Console.WriteLine("a = {0}, y = {1}", a, b);
         Console.ReadLine();
       }
    }
}


Output


Compilation error (line 8, col 18): Cannot convert null to 'int' because it is a non-nullable value type

Compilation error (line 9, col 19): Cannot convert null to 'bool' because it is a non-nullable value type


If you observe given above example, you assigned a null value to value type variables (a and b). When you execute the given above code, you will get compile-time errors, as given above.


C# Nullable Syntax


In the given syntax of declaring variables as nullable types in the c# programming language.

Nullable<N> variableName
or
N? variableName; 


Here, N is an underlying type, and it can be a non-nullable value type, and the Nullable type will represent all the values of an underlying type N and additional null value. The syntax N? is shorthand for Nullable<N> and these two forms are interchangeable.

The nullable types are generally useful when you perform database operations because sometimes, the fields in database tables will have no value or missing.


C# Nullable Type Declaration and Assignment


In the given example of declaring and assigning a value to value type variables using nullable types in c# porgramming language.

Nullable<int> x = 10;

int? a = 20;
bool? b = null;
Nullable<double> c = null;
int?[] arr = new int?[10];


In the given example of accessing a value from a nullable type instance by verifying whether it’s having a value or not using HasValue property in c# programming language.


using System;

namespace FindAndSolve
{
    public class Program
    {
       public static void Main(string[] args)
       {
          Nullable<int> a = null;
          if (a.HasValue)
          {
             Console.WriteLine("x = {0}", a.Value);
          }
          else
          {
             Console.WriteLine("Value is Empty");
          }
          Console.ReadLine();
       }
    }
}

Output

Value is Empty


If you observe the given above example, you used the HasValue property to verify whether the nullable type variable (x) is having a value or not. The HasValue property will return true only when the variable a has value; otherwise, it will return false.

In the given example of accessing nullable type value using the GetValueOrDefault() method in c# programming language.

using System;

namespace FindAndSolve
{
   public class Program
    {
       public static void Main(string[] args)
       {
          Nullable<int> a = null;
          Console.WriteLine("a = {0}", a.GetValueOrDefault());
          Console.ReadLine();
       }
    }
}


Output

a = 0


C# Assign Nullable Type to Non-Nullable Type


If you want to assign a nullable type value to a non-nullable type, then you need to use a null-coalescing operator ?? to specify the value to be assigned if the nullable type value is null; otherwise, you get a runtime exception.

In the given below example of assigning nullable type value to a non-nullable type using a null-coalescing operator ?? in c# programming language.

using System;

namespace FindAndSolve
{
    public class Program
    {
       public static void Main(string[] args)
       {
          int? a = null;
          // a = a if a is not null, b = 0 if a is null
          int b = a ?? 0;
          Console.WriteLine("b = {0}", b);
          Console.ReadLine();
       }
    }
}


Output

b = 0


If we observe given above example, you used a null-coalescing operator (??) to assign a nullable type variable a value to variable b and specified the value (0) to be assigned to variable b if nullable type variable a value is null.


C# Nullable Types Characteristics


  • Nullable types are useful to assign a null value to the value type variables.
  • Nullable types can declare like either N? or Nullable<N>. The syntax N? is shorthand for Nullable<N> and these two are interchangeable.
  • You can assign a value to nullable type like or Nullable<int> i = 5int? i = 5 or int? i = null.
  • By using a nullable type HasValue and Value properties, you can verify and retrieve the variable value like if(a.HasValue) b = i. Value.
  • The HasValue property will return true if the variable contains a value or false if it is null. The Value property will return value if the variable contains a value; otherwise, it will throw an InvalidOperationException exception.
  • You can use GetValueOrDefault() method to get the value from the nullable type. It will return the value of nullable type if it contains a value or if it is null, then it will return the default value.
  • To assign nullable type to non-nullable type, then you need to use the null-coalescing operator ??.
  • Nested nullable types are not allowed like Nullable<Nullable<int>> a