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:
Nothing<T>
? It maybe looks like Moq. And another question comes: Is it OK to use mock framework/library in product codes?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 use if(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:
public class Nothing<T> where T : class, new()
{
public static readonly T Instance = new T();
}
However, IMO that fails most of the key features of a null-object; in particular, you could easily end up with someone doing:
Nothing<Foo>.Instance.SomeProp = "abc";
(perhaps accidentally, after passing an object 3 levels down)
Frankly, I think you should just check for null
.
How about this?
public class Nothing<T> where T : class
{
public static implicit operator T(Nothing<T> nothing)
{
// your logic here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With