Wednesday, 25 August 2010

Dot.Net:Create Attribut Sample

Question:
How do I create a custom attribute in dot.net?
Do you have a simple sample for attribute creation in c# / dot.net?



Answer:
You simply create a class that inherits from System.Attribute.

Follow these steps:
  1. Create a new class
  2. Make it derive from System.Attribute
  3. Specify the usage (does this attribute applies to assembly, class, methods etc.)

Example of a simple marker attribute
using System;

[AttributeUsage(AttributeTargets.Property)]
public class MarkerAttribute : System.Attribute
{
   // you could add info here
}


You could use this attribute in order to mark certain properties in a class.
For example for custom serialization you might want to serialize only properties that are marked with your attribute.

Related: How to discover custom attributes?

No comments: