Sunday, August 12, 2007

Attributes in C# > Usage

USING ATTRIBUTES
• Attributes can be placed on almost any declaration, though an attribute might restrict the types of declarations on which it is valid

• An example of using attribute as under:
[ System.Runtime.InteropServices.DllImport( “user32.dll” ) ]
extern static void SampleMethod();


• Attributes can also have parameters, which can be either positional, unnamed or named

• Any positional parameters must be specified and can not be omitted

• Named parameters can be specified in any order and may be omitted

• In following example first parameter is positional, rest others are named and hence optional
[ DllImport(“user32.dll”, SetLastError = false, ExactSpelling = false )]

• More then one Attribute can be placed on a declaration

• Some attributes can be specified more then once for a given entity, such as Conditional

[ Conditional(“DEBUG”), Conditional(“TEST1”)]
void TraceMethod()
{ ... }

No comments:

Post a Comment