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;

        catch (NullReferenceException e)
            Console.WriteLine("EXCEPTION: "+e.Message);


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!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.