By Kamran Shakil
Attributes in Visual C#.NET are items of declarative information in our code that can be declared by us. They can be attached to any elements in the code i.e, it can be attached with a class, a method, data members or properties. Attributes are implemented by Attribute classes. Attributes are written in square brackets and written just before the element to which they are applied. Following example shows two of the most commonly used attribute:
Code
#define x
using System;
using System.Diagnostics;
namespace attr
{
class Class1
{
static void Main(string[] args)
{
test t = new test( ) ;
t.func1 ( 10 ) ;
}
}
public class test
{
[Obsolete]
int i;
[Conditional ("x") ]
public void func1( int k )
{
i = k ;
Console.WriteLine(" func1 {0} ",i) ;
}
}
}
Output :
func1 10.
And the compiler flashes two errors:
'attr.test.i' is obsolete
'attr.test.i' is obsolete
Explanation
We used two attributes viz: obsolete and conditional. obsolete marks the attribute obsolete and flashes a warning when that element is used. So when we use i in the function we get two warnings. Next we have used conditional , This means that if the specified identifier is not #defined then it cannot be accessed. Here we have #defined x, and hence we can call the function func1. If we remove the #define or #undef, the function function is not called at all.
There is one restriction of conditional attributes on methods, they can be used with only those methods which return void.