I’m wondering if there is any approach to implement generic null object pattern in C#. The generic null object is the subclass of all the reference types, just like Nothing in Scala. It seems like
public class Nothing<T> : T where T : class
But it can’t compile and I’ve no idea how to implement the methods of T to provide default behavior or throw an exception. Here are some thinkings:
- Use reflection?
- Use expression tree when creating
Nothing<T>? It maybe looks like Moq. And another question comes: Is it OK to use mock framework/library in product codes? - Use dynamic types?
I KNOW maybe I should implement particular null object for particular type. I’m just curious to know if there is any solution.
Any suggestion? Thanks.
With generics, you can’t define inheritance from
T. If your intent is to useif(x is Nothing<Foo>), then that just isn’t going to work. Not least, you’d need to think about abstract types, sealed types, and non-default constructors. However, you could do something like:However, IMO that fails most of the key features of a null-object; in particular, you could easily end up with someone doing:
(perhaps accidentally, after passing an object 3 levels down)
Frankly, I think you should just check for
null.