×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

C# - NullReferenceException Exception Example

Learn about the NullReferenceException and demonstrating the example of NullReferenceException in C#. By Nidhi Last updated : April 03, 2023

NullReferenceException Exception

Here, we are demonstrating the null reference exception. We will call a method by a reference that contains a null value. Then exceptions will be generated by the program.

C# program to demonstrate the NullReferenceException

The source code to demonstrate the null reference exception is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the null reference exception.

using System;

class ExceptionDemo
{
    void PrintHello()
    {
        Console.WriteLine("Hello World");
    }
    static void Main()
    {
        try
        {
            ExceptionDemo E = new ExceptionDemo();

            E = null;
            E.PrintHello();
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Output

Object reference not set to an instance of an object.
Press any key to continue . . .

Explanation

In the above program, we created a class ExceptionDemo that contains two methods PrintHello() and Main(). The PrintHello() message will print "Hello World" on the console screen.

In the Main() method, we created an object E in the "try" block. Then we assigned the value "null" to the reference E and then call PrintHello() method with a null reference. That's why the NullReferenceException exception gets generated and caught by the "catch"  block that will print the exception message on the console screen.

C# Exception Handling Programs »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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