Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good way to handle NullReferenceException before C# 6.0

My code below gives me a NullReferenceException and the stack trace tells me the problem is in the Count method, so I'm pretty sure at some point foo, bar or baz is null.

My code:

IQueryable<IGrouping<string, Referral>> queryable= ...;
var dict = queryable.ToDictionary(g => g.Key.ToString(),
                                  g => g.Count(r => r.foo.bar.baz.dummy == "Success"));

I'm wondering what's a concise way to handle null cases. I learn that in C# 6.0 I can just do foo?.bar?.baz?.dummy, however the project I'm working on isn't C# 6.0

like image 795
Arch1tect Avatar asked Oct 13 '15 08:10

Arch1tect


People also ask

Is NullReferenceException in C#?

The NullReferenceException is an exception that will be thrown while accessing a null object. In the above example, a NullReferenceException will be thrown in the DisplayCities() function while accessing cities list using a foreach loop because the cities list is null.

How can we avoid system NullReferenceException object reference not set to an instance of an object?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

Why am I getting a NullReferenceException?

The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference, and the reference is not initialized (or it was once initialized, but is no longer initialized). This means the reference is null , and you cannot access members (such as methods) through a null reference.

How do you handle NullReferenceException?

You can eliminate the exception by declaring the number of elements in the array before initializing it, as the following example does. For more information on declaring and initializing arrays, see Arrays and Arrays. You get a null return value from a method, and then call a method on the returned type.


1 Answers

A solution for <6.0 would be:

.Count(r => r.foo != null && 
            r.foo.bar != null && 
            r.foo.bar.baz != null && 
            r.foo.bar.baz.dummy == "Success")

Exactly for complex constructs like the one above the null propagation operator was introduced.

Furthermore you could also refactor the expression into a private method:

private Expression<Func<Referral, bool>> Filter(string value)
{
    return r => r.foo != null && 
                r.foo.bar != null && 
                r.foo.bar.baz != null && 
                r.foo.bar.baz.dummy == value;
}

and use it as follows:

g => g.Count(Filter("Success"))
like image 133
Michael Mairegger Avatar answered Sep 16 '22 17:09

Michael Mairegger