How to implement Null object Pattern in C#?


The null object pattern helps us to write a clean code avoiding null checks where ever possible. Using the null object pattern, the callers do not have to care whether they have a null object or a real object. It is not possible to implement null object pattern in every scenario. Sometimes, it is likely to return a null reference and perform some null checks.

Example

static class Program{
   static void Main(string[] args){
      Console.ReadLine();
   }
   public static IShape GetMobileByName(string mobileName){
      IShape mobile = NullShape.Instance;
      switch (mobileName){
         case "square":
         mobile = new Square();
         break;

         case "rectangle":
         mobile = new Rectangle();
         break;
      }
      return mobile;
   }
}

public interface IShape {
   void Draw();
}
public class Square : IShape {
   public void Draw() {
      throw new NotImplementedException();
   }
}
public class Rectangle : IShape {
   public void Draw() {
      throw new NotImplementedException();
   }
}
public class NullShape : IShape {
   private static NullShape _instance;
   private NullShape(){ }
   public static NullShape Instance {
      get {
         if (_instance == null)
            return new NullShape();
            return _instance;
         }
     }
      public void Draw() {
   }
}

Updated on: 25-Nov-2020

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements