C# Program to Demonstrate NullReference Exception

This is a C# Program to illustrate NullRefernce exception.

Problem Description

This C# Program Illustrates NullRefernce Exception.

Problem Solution

Here it indicates that you are trying to access member fields, or function types, on an object reference that points to null.

Program/Source Code

Here is source code of the C# Program to Illustrate NullRefernce Exception. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Illustrate NullRefernce Exception
 */
using System;
class Program
{
    static void Main()
    {
        try
        {
            string value = null;
            if (value.Length == 0) 
            {
                Console.WriteLine(value); 
            }
        }
        catch(NullReferenceException e)
        {
            Console.WriteLine(e.Message);
        }
        Console.Read();
    }
}
Program Explanation

This C# program is used to illustrate NullReference exception. Initialize an value of ‘value’ variable as null. If condition statement is used to check the length of the value of ‘value’ variable is equal to 0, if the condition is true then execute the statement.

advertisement

Indicates that trying to access member fields, or function types, on an object reference that point to null. Using try and catch, an error message is displayed when the error occurs.

Runtime Test Cases
 
Object Reference not set to an Instance of an Object

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

🎓 Free Certifications on 300 subjects are live for December 2025. Register Now!
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.