Thursday, 07 September 2006
Time tramples on and those .NET 1.1 applications that were shiny and new just a few years ago are probably beginning to show their age.  Improvements and refinements in every application or class library have probably left behind a goodly number of dead and dying methods, or even whole classes.  This is probably even more true of 1.1 applications that were ported to 2.0 and since refactored to take advantage of new .NET features. 

While ripping out all these methods before some newbie team member (or forgetful old hand) accidentally uses one would be ideal, this is not always a practical solution. But there is an easy way to warn off developers while planning for eventual refactoring, the Obsolete Attribute.

Marking a method, property, field, class or interface with the Obsolete Attribute will generate a compiler warning, and Visual Studio will clearly mark each offending use of the "soon" to be removed member.  Best of all, it easy is to use. 

In C#...
[Obsolete("This method has been replaced by ReallyUsefulMethod.")]
public void OnceUsefulMethod(){

ala VB.NET (don't forget the line continuation)...
<Obsolete("This method has been replaced by ReallyUsefulMethod.")> _
Public Sub OnceUsefulMethod()

That's all there is to it. If it's called any place, a compiler warning will be generated, and Intellisense will also display its impending doom.

If for some reason, the method needs to be taken out of use immediately (for a security concern, etc.) , the Obsolete Attribute can also generate a compiler error using the code below.  The second argument to the constructor if set=true will generate an error instead of a warning.

In C#...
[Obsolete("This method has been replaced by ReallyUsefulMethod.", true)]
public void OnceUsefulMethod(){

ala VB.NET...
<Obsolete("This method has been replaced by ReallyUsefulMethod.", True)> _
Public Sub OnceUsefulMethod(){

Using this attribute is also a quick and dirty way to find out all the places in an application a particular code element is being used.  Compile the application they'll all be nicely listed in the task list.

The Obsolete Attribute -- an easy to use, graceful first step in pruning and refactoring -- try it today!

Thursday, 07 September 2006 09:14:07 (Eastern Standard Time, UTC-05:00)   #     Comments [0]  | 

Theme design by Dean Fiala

Pick a theme: