When is NotImplementedException Appropriate?

The purpose of NotImplementedException in C#

In C#, NotImplementedException is an error type that’s specifically designed to be thrown from the members that implement the interface but aren’t intended to be used. It comes directly from the core system library of C#.

At first glance, it might seem that with this feature in place, the language was designed to violate the interface segregation principle. However, there are situations where leaving unused interface methods in your class will be appropriate without necessarily violating this principle.

Situation 1: Work in progress implementation

One situation where throwing NotImplementedException will be appropriate is if your class is a work in progress and this has been put there temporarily. You can decide on all the essential members for your class ahead of time and create the interface immediately before you forget what you intend to do.

However, creating the class might take a relatively long time, and you might not be able to do it all in one go. Despite this, you’ll already have to implement every interface member. Otherwise, your code won’t compile. Gradually, you’ll populate every member with some valid logic.

Because every interface member is intended to eventually be implemented and is absolutely required for the finished product, this won’t violate the interface segregation principle.

Situation 2: Interface implementation for easy testing

The other case is when you want to write an interface implementation to enable easy testing of your code. You might have an original class that’s intended to be placed in production. This class might have various pieces of logic that you won’t be able to replicate on a development machine. For example, it might be sending requests to a certain server or reading messages from a certain queue. In that class, every method and property is absolutely required to be there.

However, there can be some pieces of functionality in the class that you would be able to run anywhere. So, you can have a version of the class that only contains those components, which will allow you to easily run certain tests on any machine.

This is where NotImplementedException serves its purpose. In this context, it’s there to notify the developer that, although this method or property is an essential member of the class under normal circumstances, it’s not relevant in this specific context.

The alternative would be to mock those methods up, but doing so would give them logic that’s completely different from how the production class behaves. Therefore, the behavior you’ll see in your tests won’t be representative of the actual behavior of the deployed software, and the tests may be pointless. However, the methods that are testable will behave exactly as they would in production.

Get hands-on with 1200+ tech skills courses.