Ways to Avoid
Explicitly check for null and ignore null values.
If you expect the reference sometimes to be null, you can check for it being null before accessing instance members:
void PrintName(Person p)
{
if (p != null)
{
Console.WriteLine(p.Name);
}
}
Explicitly check for null and provide a default value.
Methods call you expect to return an instance can return null, for example when the object being sought cannot be found. You can choose to return a default value when this is the case:
string GetCategory(Book b)
{
if (b == null)
return "Unknown";
return b.Category;
}
Explicitly check for null from method calls and throw a custom exception.
You can also throw a custom exception, only to catch it in the calling code:
string GetCategory(string bookTitle)
{
var book = library.FindBook(bookTitle); // This may return null
if (book == null)
throw new BookNotFoundException(bookTitle); // Your custom exception
return book.Category;
}
Use Debug.Assert if a value should never be null, to catch the problem earlier than the exception occurs.
When you know during development that a method maybe can, but never should return null, you can use Debug.Assert() to break as soon as possible when it does occur:
string GetTitle(int knownBookID)
{
// You know this should never return null.
var book = library.GetBook(knownBookID);
// Exception will occur on the next line instead of at the end of this method.
Debug.Assert(book != null, "Library didn't return a book for known book ID.");
// Some other code
return book.Title; // Will never throw NullReferenceException in Debug mode.
}
Use GetValueOrDefault() for nullable value types to provide a default value when they are null.
DateTime? appointment = null;
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the default value provided (DateTime.Now), because appointment is null.
appointment = new DateTime(2022, 10, 20);
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the appointment date, not the default
Use the null coalescing operator: ?? [C#] or If() [VB].
The shorthand to providing a default value when a null is encountered:
IService CreateService(ILogger log, Int32? frobPowerLevel)
{
var serviceImpl = new MyService(log ?? NullLog.Instance);
// Note that the above "GetValueOrDefault()" can also be rewritten to use
// the coalesce operator:
serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
}