
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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() { } }
- Related Questions & Answers
- How to implement IDisposable Design Pattern in C#?
- How to implement a Singleton design pattern in C#?
- How to implement Builder pattern in Kotlin?
- What is proxy design pattern and how to implement it in C#?
- The Null Object in Python
- Set JavaScript object values to null?
- JavaScript/ Typescript object null check?
- Calling a member function on a NULL object pointer in C++
- Adapter Pattern in C++?
- 132 Pattern in C++
- Word Pattern in C++
- How to implement operator overloading in C#?
- How to use Null Coalescing Operator (??) in C#?
- How to capture null reference exception in C#?
- Program to print Interesting pattern in C++
Advertisements