Tuesday, June 22, 2010

How to Show Obsolete Code Warning to users in .Net

If you've been using the .NET Framework for a number of years chances are you've seen the Framework versions advance and seen instances where some of the .NET Framework classes such as prior Configuration classes have gone obsolete and you've received warnings from the compiler about it to make you aware. You may have wondered how to do that same thing with your own code. There is an Obsolete attribute that you can use to decorate your own classes and methods to indicate they are being phased out as well. If you're working independently of others, then chances are you won't need it. However, in working with a project team where you may have implemented a framework, helper classes or other conventions, it can be very helpful to use the Obsolete attribute to flag dead code that won't be used going forward. This allows them to be migrated over time rather than just deleting from your code. This is very handy as you refactor code to communicate through the compiler that a particular item is obsolete. By default the items are served up as warnings, but an optional flag can indicate if they should be treated as warnings. It is worthwhile to have that setting be a configuration value so that you can enable or disable it across the board.

// Include message for compiler to present
[Obsolete("This class is dead. It has been replaced by MyClass3.")]
class MyClass1
{
// ...
}

// Include message and generate a compiler error
[Obsolete("This class is dead. It has been replaced by MyClass4. "), true]
class MyClass2
{
// ...
}

No comments: