Object Reference Not Set to an Instance of an Object in C#

Understanding the “Object Reference Not Set to an Instance of an Object” Error in C#

Yohan Malshika
4 min read3 days ago

The “Object reference not set to an instance of an object” is one of the most common runtime exceptions in C# development. If you’ve ever worked with C#, you’ve likely encountered this error at least once. Despite its frequent appearance, this exception can frustrate both beginners and experienced developers. Let’s explain what it means, why it happens, and how to fix or prevent it.

What Does the Error Mean?

In C#, all reference types (such as classes, arrays, and strings) need to be initialized or assigned memory before being used. If you attempt to access a method, property, or field of an uninitialized object (i.e., an object that is null), the runtime will throw a NullReferenceException, with the message "Object reference not set to an instance of an object."

Simply, this error tells you that you’re trying to use an object that has not been instantiated.

Example of the Error

class Person
{
public string Name { get; set; }
}

void Example()
{
Person person = null;
Console.WriteLine(person.Name); // Throws "Object reference not set to an instance of…

--

--