Monday, April 24, 2023

What is a NullReferenceException in C# ?

A 'NullReferenceException' is a type of exception in C# that occurs when you try to access or manipulate an object that is null. In other words, when you try to call a method or access a property or field of an object that is null, the runtime throws a 'NullReferenceException'.

Here's an example:
string str = null;
int length = str.Length; // This line will throw a NullReferenceException
In the above example, we are trying to access the 'Length' property of a 'string' object that is 'null'. This will cause a 'NullReferenceException' to be thrown at runtime.
To avoid 'NullReferenceException', it's important to ensure that any object you use is not 'null' before accessing its members. You can use null-conditional operator ('?.') and null-coalescing operator ('??') to handle null values in a safer way.
string str = null;
int length = str?.Length ?? 0; // This code will not throw exception as str is null-safe and returns 0
In this example, the '?.' operator checks if the 'str' object is null and returns null instead of throwing an exception. The '??' operator provides a default value of 0 if the 'Length' property is null.

No comments:

Post a Comment