.NET Framework, what is obsolete attribute in .NET framework.
What is Obsolete attribute in .NET framework:
The attribute "Obsolete" is used to mark a program element-entity (such as classes, methods or other entries) in an assembly that is no-longer being used.
How to use Obsolete attribute in C#:
In order to mark a entity as Obsolete, following syntax is used.
[Obsolete("Please do not use this method in your app.: Application stops working in Windows 7",true)]
Why to use Obsolete attribute in .NET framework:
A Class library which contains methods can get an update to its methods as the updated version of method to perform the same task. For example, following Class library as moderation. The following example source codes demonstrates how to use "Obsolete" attribute in C# to mark a method. Old developer codes the method1 and works till release of Windows7. New developer which took over the project marks the method as "Obsolete". Other developers who work on same project, will be informed when they try to access this method at the compile stage.
Following example demonstrates how to use obsolete attribute in C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Data;
namespace ConsoleApplication4
{
class Program
{
static void Main(string [] args)
{
//create and initialize an instance of Class///
CL_SQLgenericTasks o_exampleObject = new CL_SQLgenericTasks();
//call method1 which is marked as obsolote///
//due to being marked as obsolote with note, compiler provides warning message///
o_exampleObject.clf_method_1();
}
}
public class CL_SQLgenericTasks
{
//Marked method1 as obsolote with following attribute///
[Obsolete("Please do not use this method if your app. runs in Windows 7")]
//old method used to work with XP, causes error in windows7///
public void clf_method_1()
{
}
//a new method is added later to DLL by developer///
public void clf_method_1new_windows7version()
{
}
}
}
Method above in example is marked as obsolete. Screen-shot of compile from Visual Studio.
How to use Obsolete attribute in C# to prevent a method to be used, to indicate with error message on access:
Obsolete attribute can be also used to provide error message at compile time to prevent the compile. To mark a method for not being used: following syntax can be used.
[Obsolete("Please do not use this method in your app: it does not work in Windows 7",true)]
Image from compile screen which demonstrates "true" added result. VS prevents the compilation when the method is tried to be accessed.