Have you ever started out writing code one way and later discover that another way is much, much better? It happens to me daily. I face a difficulty, sometimes, when I want to refactor my code into a more concise, elegant form, but some of my teammates already use the existing methods.

One neat feature of C# is the ability to decorate methods and other structures in code. A useful decoration for this situation is the Obsolete decoration. Here are several examplse:

[Obsolete]
void ObsoleteMethod1() { }

[Obsolete("This is why we don't use this...")]
void ObsoleteMethod2() { }

[Obsolete("If you use this, there will be compile errors", true)]
void ObsoleteMethod3() { }

The description comes in handy because it will show up in the tooltip when typing in the method in Visual Studio. This ensures that it is not necessary for developers to have source code to detect whether a method should be discontinued.

Descriptions specified in the Obsolete decoration appear in the tooltip

You can also forcefully terminate the use of the method without blindly removing it. The third sample demonstrates this. Using the ObsoleteMethod3 method would cause a compile-time error. This provides a good opportunity to discontinue a method and provide an explanation as to why it is no longer used.

Happy coding!


 
Comments are closed.