C# – Is it possible to throw compiler error when attempting to use an unimplemented method

cvisual studio

The backstory is long but the general idea is that I'm beginning an iterative refactoring process to replace a poorly designed data access layer with a new one under constraints from above. We can't fix everything at once but need to slowly phase in the new changes.

The old DAL contains several classes each containing several data access methods. The new DAL must preserve the method signatures and return types of the old DAL, and the old DAL code must be retained through the refactor. In a way you could say that we're implementing a repository pattern after the fact but also hard coding the dependencies on a method by method basis instead of injecting them at runtime.

A nice way to go about the refactor is with VS Quick Actions. I can easily extract an interface from each of the old classes through the designer and then auto-implement them for the new classes. This creates a new class with the same method signatures of the old class; however the new methods are initially just stubs that throw a NotImplementedException until they are filled with an implementation.

The trouble is that the NotImplementedException is only thrown at runtime whereas I really need it at compile time. Is there a pattern that can be used to allow us to stub out the new DAL methods but raise a compiler error if we attempt to use them before they are in fact implemented?

Best Answer

Someone had posted earlier about the Obsolete attribute, which can be configured to throw an compile error when attempting to use a method that is decorated as such. I don't know why that answer got deleted but it works perfectly for my purposes. Thanks, whoever you are!

    [Obsolete("This method has not yet been implemented.", true)]
    public IList<object> MyMethod()
    {
        throw new NotImplementedException();
    }
Related Topic