Home » C#

NullReferenceException Exception in C#

C# NullReferenceException Exception: Here, we are going to learn what is NullReferenceException Exception and how to handle NullReferenceException Exception in C#?
Submitted by IncludeHelp, on September 21, 2019

What is NullReferenceException?

NullReferenceException is an exception and it throws when the code is trying to access a reference that is not referencing to any object. If a reference variable/object is not referencing to any object, then it will be considered as null. And, when the code tries to access this variable/object, there will be an exception known as NullReferenceException.

To handle NullReferenceException, we can write the code/message in catch block by using 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 created a class "Sample" that contains a Method SayHello(), then we created another class that consumes class "Sample", then we create a reference of class "Sample" and assign null to reference s. We further called the method SayHello() using reference s, but it is not initialized properly. Thus, it generates NullReferenceException which is being caught in the catch block.

Read more:



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.