Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic null object pattern in C#

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:

  1. Use reflection?
  2. 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?
  3. 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.

like image 395
Kirin Yao Avatar asked Jul 05 '12 07:07

Kirin Yao


2 Answers

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.

like image 102
Marc Gravell Avatar answered Sep 22 '22 20:09

Marc Gravell


How about this?

public class Nothing<T> where T : class
{
     public static implicit operator T(Nothing<T> nothing)
     {
          // your logic here
     }
}
like image 28
abatishchev Avatar answered Sep 24 '22 20:09

abatishchev