NullReferenceException Exception in C#

C# NullReferenceException Exception: Here, we will realize what is NullReferenceException Exception and how to deal with NullReferenceException Exception in C#?

What is NullReferenceException?

NullReferenceException is a special case and it tosses when the code is attempting to get to a reference that isn’t referencing to any object. On the off chance that a reference variable/object isn’t referencing to any object, at that point it will be considered as invalid. What’s more, when the code attempts to get to this variable/object, there will be an exemption known as NullReferenceException.

To deal with NullReferenceException, we can compose the code/message in get block by utilizing the NullReferenceException class.

Example of NullReferenceException in C#:

using System;

class Sample
{
    public void SayHello()
    {
        Console.WriteLine("Hello World");
    }
}

class Program
{
    static void Main()
    {
        Sample s = null;

        try
        {
            s.SayHello();
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine("EXCEPTION: "+e.Message);
        }
    }
}

Output:

EXCEPTION: Object reference not set to an instance of an object

In the above program, we made a class “Test” that contains a Method SayHello(), at that point we made another class that devours class “Test”, at that point, we make a reference of class “Test” and allot invalid to reference s. We further called the strategy SayHello() utilizing reference s, however, it isn’t instated appropriately. In this way, it creates NullReferenceException which is being trapped in the catch block.

Leave a Comment

error: Alert: Content is protected!!