What is Nullable types in C#

What is nullable type in C# code? Please explain with an example.

Nullable types were introduced in C# 2.0.
Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the range of values for its underlying data type, also an additional null value.

For example, a Nullable<Int32>, pronounced “Nullable of Int32,” can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value.

A Nullable<bool> can be assigned the values true, false or null.

Try below code :
class NullableTypeExample
{
static void Main()
    {
        int? number = null;
        if (number.HasValue == true)
        {
            System.Console.WriteLine(“Value= ” + number.Value);
        }
        else
        {
            System.Console.WriteLine(“number = Null”);
        }

        // y is set to zero
        int y = number.GetValueOrDefault();
//number.Value throws an InvalidOperationException if num.HasValue is false
        try
        {
            y = number.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}

Leave a Comment

RSS
YouTube
YouTube
Instagram