Sharper Learning Attributes


Attributes in Visual C#.NET are items ofdeclarative information in our code that can be declared by us. Theycan be attached to any elements in the code i.e, it can be attachedwith a class, a method, data members or properties. Attributes areimplemented by Attribute classes. Attributes are written in squarebrackets 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 andconditional. obsolete marks the attribute obsolete and flashes awarning when that element is used. So when we use i in the function weget two warnings. Next we have used conditional , This means that ifthe specified identifier is not #defined then it cannot be accessed.Here we have #defined x, and hence we can call the function func1. Ifwe remove the #define or #undef, the function function is not called atall.

There is one restriction of conditional attributes on methods, they can be used with only those methods which return void.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!