Home > .NET, C# > Some Useful C# attributes

Some Useful C# attributes

S.No. Attribute Description & Usage
1. Obsolete Marks a program entity (method, property, field, etc) that should not be used.  This is useful to make an old/ unwanted/ outdated method as not usable one without removing or commenting it.

[Obsolete]
Public  method OldCompute(int x, int y)
{

}

-  above code give a warning message during compilation


[Obsolete("Do not use this method", true)]

-   above code will give error message with given message

2. Category It groups a property under a category in property grid.
3. Description It is used to set description to a property

[Category("Appearance")]

[Description("The caption")]
Public  string Caption
{
get  { return _caption; }
set  { _caption = value; }
}

4. Conditional It defines a method whether it will be executed or not when a call.

#define “Debug”
..
..
[Conditional("Debug")]
public  void  LogMsg(string  msg)
{

}
..
..
LogMsg(“reached here”)
..
#undef “Debug”
..
..
[Conditional("Debug")]
public  void  LogMsg(string  msg)
{

}
..
..
LogMsg(“reached here”)
..
Here the LogMsg method will be executed Here the LogMsg method will not be executed
5. DllImport It is used to import an external dll or API

using System.Runtime.InteropServices;
public class test
{
[DllImport("kernel32.dll")]
public static extern bool Beep(int frequency,int duration);
static void Main()
{
Beep(1000,111);
}
}

6. CLSComplaint It is used to tell the compiler to check whether the code is CLSComplaint or not. If it is true the compiler will give warning message for non-CLSComplaint code.

[assembly:CLSCompliant(true)]

the above attribute’s target is assembly.

[CLSCompliant(true)]

the target can be a class or method and before this it is must to set assembly level CLSCompliant attribute.

Advertisement
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.