- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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() { } }
Advertisements