Nullable Reference Types (NRT’s) in C# 8.0

As we know, we can store Null values in reference types in C#. We will get the error if we perform some operation on Null variables without checking its value. For example, consider the below code where we are trying to display string type variable length, which has Null value.

namespace NullableReferenceTypesExp
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = null;

            GetStringLength(str);
        }

        private static void GetStringLength(string str)
        {
            int len = str.Length;

            Console.WriteLine(len.ToString());
            Console.ReadLine();
        }
    }
}

We are not checking whether string variable str has value or Null before finding its length, and we get the error as “Object reference not set to an instance of an object” at run-time. Before C# 8.0, the compiler won’t give any warnings at compile-time about variable has Null value.

In C# 8.0, we can resolve this issue by enabling the nullable tag (#nullable) at the start of the class. C# 8.0 officially supported for .Net Core only, but we can it for .Net Framework also by editing .csproj file and adding below property group.

<PropertyGroup>
    <LangVersion>latest</LangVersion>
    <Nullable>enable</Nullable>
  </PropertyGroup>

Enable nullable by declaring #nullable enable the top of the class, as shown below.

namespace NullableReferenceTypesExp
{
    #nullable enable
    class Program
    {
        static void Main(string[] args)
        {
            string str = null;

            GetStringLength(str);
        }

        private static void GetStringLength(string str)
        {
            int len = str.Length;

            Console.WriteLine(len.ToString());
            Console.ReadLine();
        }
    }
}

After enabling nullable, if you observe C# shows the warning while using the Null variable as shown below.

 

We can disable nullable by declaring the #nullable disable tag at the class level.

                                                                           NullableReferenceTypesExp.zip (22.72 kb)