Articles → .NET DESIGN PATTERN → Null Object Design Pattern

Null Object Design Pattern






Purpose





Scenario




public class MemberEntity
{ 
   public virtual int Id { get; set; }
   public virtual string FullName { get; set; }
   public virtual string Email { get; set; }
}





MemberEntity memberEntityObject = null;
Console.WriteLine(memberEntityObject.Id);





Picture showing the error message when initializing the class without using the null object design pattern
Click to Enlarge


Null Object Design Pattern Comes Into The Picture




public class MemberEntity
{
  public static readonly MemberEntity NULL = new NullMemberEntity();

  public virtual int Id { get; set; }
  public virtual string FullName { get; set; }
  public virtual string Email { get; set; }
}
class NullMemberEntity : MemberEntity
{
  public override int Id => 0;
  public override string FullName => string.Empty;
  public override string Email => string.Empty;
}





MemberEntity memberEntityObject = MemberEntity.NULL;
Console.WriteLine(memberEntityObject.Id);




Output


Picture showing the output of the null object design pattern
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, August 30, 2011
 
Updated On  -  Tuesday, July 25, 2023

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250