What is Nullable types in C#

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

Nullable types was 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);
        }
    }
}

Comments

Popular

C# 6.0 New Features

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners