C# Nullable Type Variables

Updated on     Kisan Patel

You can assign the normal range of values as well as a null value to a nullable type. These values are specified for the underlying value type of the nullable type.

For Example, you can assign a value from -2147483648 to 2147483647 or null value to Nullable<Int32>. You can assign the values true, false or null to Nullable<bool>.

To understand this concept better see below C# code:

class Program
 {
      public static void Main(string[] args)
      {
              int? var1 = null; // Declare nullable type variable
              //here int? is Nullable where underlying type is int

              Nullable var2 = null;

              Console.WriteLine("var2 = " + var2);

              int digit = 5;
              var1 = digit;

              if (var1.HasValue == true)
              {
                      Console.WriteLine("var1 = " + var1);
              }
              else
              {
                      Console.WriteLine("var1 = Null");
              }

              Console.ReadLine();
       }
 }

the output of the above C# program…

nullable-type-c-sharp


C#

Leave a Reply