Prizes & Awards
My Profile
Active Members
TodayLast 7 Days
more...
|
Resources » Articles » General »
Attributes in C#
|
Attributes can be used to encapsulate information about classes, methods etc. There are many predifined attributes like [Obsolete], [Serializable], [NotSerialized] that server different purposes.
We can create our own attributes for using with classes and methods. Name of Attribute classes convensionally ends with the Attribute word.
Definition of Attribute Class -------------------------------- [AttributeUsage] attribute can be used to specified for what purpose the attribute class is going to be used.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] class CodeAttribute : Attribute { string name; string type; string author; int mversion, sversion; DateTime dateWritten; public CodeAttribute(string Name, string Type) { this.name = Name; this.type = Type; }
public DateTime DateWritten { get { return dateWritten; } set { dateWritten = value; } } public string Name { get { return name; } } public string Type { get { return type; } } public string Author { get { return author; } set { author = value; } } public int MVersion { get { return mversion; } set { mversion = value; } } public int SVersion { get { return sversion; } set { sversion = value; } } }
The above code defines a class "CodeAttribute" with some properties and fields.
Using Attributes ----------------
The following code demonstrates how to use the 'CodeAttribute' attribute with classes.
Eventhough the class is named "CodeAttribute" it can be referred to as "Code" (omiting "Attribute").
[Code ("Test","Class",Author="Anil")] [Code ("Test","Class",Author="Mahesh")] class Test {
}
Here the class 'Test' is having a two code attributes with different values.
In the following code the CodeAttribute is applied on a method "MyMethod".
public class Program { [Code("MyMethod", "Method", Author = "Anil", MVersion = 1, SVersion = 2)] public static void MyMethod() { } }
Now let us see how these values can be accessed at runtime.
public static void Main(string[] args) { Test tst = new Test(); Type t = tst.GetType(); object[] ar = t.GetCustomAttributes(true); foreach (Attribute a in ar) { if (a is CodeAttribute) { CodeAttribute attr = (CodeAttribute)a; //a as CodeAttribute; Console.WriteLine("Name :{0} Type :{1} Author :{2} Version:{3}.{4}", attr.Name, attr.Type, attr.Author, attr.MVersion, attr.SVersion); } } }
|
Responses
|
No responses found. Be the first to respond and make money from revenue sharing program.
|
|