Skip to content

Instantly share code, notes, and snippets.

@rickyah
Last active August 29, 2015 13:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickyah/10016784 to your computer and use it in GitHub Desktop.
Save rickyah/10016784 to your computer and use it in GitHub Desktop.
csharper_attributes

#C# Attributes

WIP

Attributes are just meta-data associated to the code.

You can create your own:

  • Create a child class of System.Attribute
  • The name of your attribute class should end with Attribute (convention sufix)
    • Omit the subfix when actually using the attribute.
  • (optional) Use the AttributeUsage attribute to specify to which constructions the attribute may apply to (Class, Interface, Methods, Constructors...)

Example:

[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public MyOwnAttribute : System.Attribute
{
}

...

[MyOwn]
public class MyClass
{

   [MyOnw]
   public MyClass() 
   {
   }
}

AttributeTargets reference

Some useful attributes

####ObsoleteAttribute

Marks a class / method / interface as obsolete. The compiler will throw a warning each time we reference the construct.

[Obsolete]
int DeprecatedMethod()
{
}

Although it is optional, it is highly recommended that you leave a meaningful warning message:

[Obsolete("To be deprecated in v1.1. Use NewMethod instead")]
int DeprecatedMethod()
{
}

####ConditionalAttribute

Compiles a method (or class) iff a preprocessor variable is set.

// The conditional method MUST NOT return any value (void)
[Conditional("DEBUG")]
void ConditionalMethod()
{
}

The above code is equivalent to:

#if DEBUG
void ConditionalMethod()
{
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment