In .NET, whenever an interface is generated, the method stubs are filled in with “NotImplementedException”s. We might also use these exceptions elsewhere, for example, constructing pre-test class methods, or deferring implementation of some functionality. For actual circumstances where some behavior cannot be performed, use NotSupportedException instead.
It’s easy to do a search for NotImplementedException, or use the VS Code Analysis tool to detect uses, but these both require a special effort, and NotImplementedExceptions may be lost or accidentally slip into production builds.
To avert this, here is an easy way to cause the compiler to generate a warning everytime it encounters a NotImplementedException. Add this code to a file anywhere in your project.
namespace System { #if DEBUG [Obsolete("Replace NotImplementedException with NotSupportedException, or implement")] public class NotImplementedException : Exception { public NotImplementedException() : base() { } public NotImplementedException(string message) : base(message) { } } #endif }
We use the System namespace to “override” the default implementation of NotImplementedException. We use the Obsolete attribute because it generates a compiler warning automatically. In other words, these are bad things to do in general, but serve a pragmatic purpose here.
Unfortunately, we cannot make partial classes across assemblies, so there will be an additional warning that the NotImplementedException defined here conflicts with the mscorlib.dll’s implementation. However, since the overall goal is to generate warnings, this is acceptable. These warnings will disappear once all NotImplementedException references are removed.
Every case where a NotImplementedException is used, whether by an auto-generated stub or some other reason, will produce this compiler warning:
Warning 27 'System.NotImplementedException' is obsolete: 'Replace NotImplementedException with NotSupportedException, or implement'
In addition, when in a code file using NotImplementedException, a warning marker will be shown. Mousing over suggests to change the exception.
Implementing the feature, or changing the exception to NotSupportedException, removes the warning.