Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Null Object in C#

Martin Fowler's Refactoring discusses creating Null Objects to avoid lots of

if (myObject == null)

tests. What is the right way to do this? My attempt violates the "virtual member call in constructor" rule. Here's my attempt at it:

public class Animal
{
    public virtual string Name { get; set; }
    public virtual string Species { get; set; }
    public virtual bool IsNull 
    { 
        get { return false; }
    }
}

public sealed class NullAnimal : Animal
{
    public override string Name
    {
        get{ return "NULL"; }
        set { }
    }
    public override string Species
    {
        get { return "NULL"; }
        set { }
    }
    public virtual bool IsNull
    {
        get { return true; }
    }
}
like image 806
Sisiutl Avatar asked Jul 24 '09 15:07

Sisiutl


1 Answers

Go look up the amount of pain that interesting concepts, such as DbNull, have caused and think about if this is actually a good idea.

Protip: if you are constantly checking for null references, you probably should rethink the API a bit to help preclude null objects closer to the top of the stack.

Protip II: having something throw an exception when there is an unexpected null is actually fine and dandy. Things should go boom if you have nulls where there shouldn't be null.

like image 70
Wyatt Barnett Avatar answered Sep 21 '22 08:09

Wyatt Barnett