Pages

Tuesday, September 27, 2011

Usage of Obsolete attribute

Recently I came across a fine technique to mark your old code as obsolete in C#. I did some research work and Book called the same as an Insert attribute.Leaving the theory apart the practical was was that interested me the most and here I present an example of the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Types
{
class Program
{
enum weekdays {mon=1,tue,wed,thurs,fri,sat,sun}

//Use of obsolete attribute to mark a function a obsolete
[Obsolete("Use newmethod", true)]
static void oldmethod()
{
Console.WriteLine("No");
}

static void newmethod()
{
Console.WriteLine("Yes");
}

public static void Main(string[] args)
{
int x = (int)weekdays.wed;
Console.WriteLine("The wednesday Enum value is {0}",x);
newmethod();
}
}
}

now when I call "oldmethod()" It gives an error with a message specified as in the code...

and on calling "newmethod()" it runs fine

I peeped more into their family and found following attributes also as a part which I will discuss later

AttributeUsage
AttributeTargets
Conditional
Obsolete as discussed in this post...

No comments:

Post a Comment