# Friday, November 06, 2009
« New features of VS2010 which have me smi... | Main | New features of VS2010 which have me smi... »

There comes a time when old code needs to be laid to rest. For example, as I migrate applications to VS2008, I find myself converting common functions to extension methods where it makes sense to take advantage of the new language functionality. Lately, I have been doing this a LOT.  I don’t want to have to maintain separate libraries for each version, but I am also not doing much development in older versions of .Net either.

Fortunately, .Net provides us with the ability to make old code obsolete. We have two options with this:

  1. Make it so users can still use the functionality, but inform them new functionality exists
  2. Require them to use the new functionality


There is an attribute called “System.Obsolete” which allows us this option. It can be used on a most anything (classes, properties, functions, structs, etc), and has the following syntac in C#:

[System.Obsolete(“Some description – provide the new recommended way”, true/false)]

The true/false (defaults to false) parameter indicates if you want to create a compilation error if this method is used. I do wonder about the usefulness of this paramter though, as at that point, why not make sure it’s in source control and delete it? I guess for historical purposes it might make sense to keep it.

 

    public class TestClass

    {

        [System.Obsolete("Use NewMethod()")]

        public void OriginalMethodStillAvailable()

        {

            //Do Something...

        }

 

        [System.Obsolete("Use NewMethod()", true)]

        public void OriginalMethodNotAvailable()

        {

            //Do Something...

        }

 

        public void NewMethod()

        {

            //Do Something...

        }

 

    }

 

If you try to use the method which is marked obsolete, but allowed, you'll see something like this:

 

 

If you try to use one with the obsolete flag set to true, you'll see a compilation error like this:

 

 

Comments are closed.