The Null Object Pattern in C# and System.Lazy
April 6th, 2012 by Chris Missal
This post is going to cover a pair of topics that aren’t truly related, but topics that I like to use together. When combined they can give you a nice pattern. First I’m going to briefly talk about the Null Object Pattern:
The Null Object Pattern
Rather than dealing with uninitialized variable instances, you can start off by assigning a variable to an instance of a “Null Object”. Oftentimes you’ll see this done when developers assign an empty string to a variable because they don’t want to deal with null values. I’m going to be discussing this with types that are a bit more complex than string.
In the code snippet below, I have represented a method with an optional argument that will fall back to an “empty” signature if one isn’t supplied. This Empty property is our Null Object for Signature that provides a safe instance we can use instead of dealing with null.
public void ApplySignature(Signature signature = null){ var signatureToApply = signature ?? Signature.Empty;
// sign things...}
public class Signature{ public Signature(EmailUser user) : this() { if (user == null) throw new ArgumentNullException("user", "A Signature must be created for a valid user");
User = user; }
private Signature() { RichText = ""; }
public EmailUser User { get; private set; }
public string RichText { get; set; }
public static Signature Empty { get { return new Signature(); } }
public override string ToString() { return RichText; }}