LINQ SingleOrDefault and NullObject
Suppose you have this simple class (has no business meaning is valid only as example)
|
|
It is a simple class with two properties and a method Greet(). It use the null object pattern, because it defines an object with Value=-100 and Name=String.Empty as the NullValue. But how this object works with LINQ? Try this code:
|
|
Ooopps, this raise a NullReferenceException, because the second LINQ query searches for an object called “someother”, it does not find any object that satisfy the query, then the SingleOrDefault() returns null, and here it is the exception. The question is, “is there a way to make SingleOrDefault returns my null object instead of null?”. The answer is straightforward
|
|
This extension method is more specific than the generic SingleOrDefault<TSource>(this IEnumerable<TSource> ) defined in the System.Linq.Enumerable extension class, so it gets called instead of the default one when the source contains MyObject and not general objects. The method use the base implementation of the SingleOrDefault, but with the use of the ?? operator, it changes null into your null object instance. Now if you run the sample again you will obtain.
|
|
And you can see that now the null object Greet() function is called.
alk.