Showing posts with label Null Reference Exception. Show all posts
Showing posts with label Null Reference Exception. Show all posts

Wednesday, 3 August 2022

What is a NullReferenceException?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Many different kinds of exceptions occur NullReferenceException is one of the exceptions which occurs.

NullReferenceException occurs when you try to use something that is null. This means the value is either set to null, or the value is never set to it.

Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A".

null can have different meanings:

1. Object variables that are uninitialized and hence point to nothing. In this case, if you access members of such objects, it causes a NullReferenceException.

2. The developer is using null intentionally to indicate there is no meaningful value available. 

To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. If an object can return null, simply check that object's value before trying to access the properties/methods. I would never allow an exception to be thrown and interrupt the standard program flow just to catch an Exception and log it.

Example of null reference

Check whether an object contains a null value or not using an if condition, as shown below:

public class Program
{
public static void Main()
{
IList<string> companies = null;
DisplayCompany(companies);
}

public static void DisplayCompany(IList<string> companies)
{
if (companies == null) //check null before accessing
{
Console.WriteLine("No companies");
return;
}

foreach (var company in companies)
{
Console.WriteLine(company);
}
}
}

In the above example, if(companies == null) checks whether the companies object is null or not. If it is null then display the appropriate message and return from the function.