How to Define Custom Attributes in C# (C Sharp)

If you want to associate any additional information with the programming objects like class or structures, you can store them as attributes. These attributes will be processed by the compiler and stored in metadata.Attributes can be classified into Pre-defined Attributes and Custom Attributes.

Pre-defined attributes are used to store external information into metadata. For example, consider the following piece of code:

public class testAttribute {
[DllImport("sampleDLL.dll")]
public static extern sampleFunction(int sampleNo, string sampleString );
public static void Main( ) {
string strVar;
sampleFunction(10, “Test Attribute”);
}
}


Using the example code above, you can import a method called sampleFunction from sampleDLL.dll and use it in your program as if it’s your own method. This is achieved using the pre-defined attribute “DllImport”. Yet another example of pre-defined attributes is “Conditional” attribute.

In certain cases, you might want to create and use your own attribute. You can very well do it in C# by defining custom attributes. To create custom attribute, follow the guidelines given below:

• Your attribute can be visible to all programming objects or visible and accessible only to specific programming objects. You can specify this visibility by using AttributeUsage attribute which should be specified before defining your attribute. If you want your attribute to be visible to all programming objects, use the following line of code:

[System.AttributeUsage(System.AttributeTargets.All)]

If your attribute has to be visible only to classes then specify the following code:

[System.AttributeUsage(System.AttributeTargets.Class]

If your attribute has to be visible to both structures and classes but not to any other programming objects then specify the following code:

[System.AttributeUsage(System.AttributeTargets.Struct |System.AttributeTargets.Class)]

• You have to define a new class for creating custom attribute.
• The corresponding attribute class should have its access modifier as public.
• Attribute class should derive from System.Attribute or any of its derived classes.
• Attribute class should have minimum one constructor with access modifier as public.
• Attribute class can have parameters which are classified into:

o Positional: These are mandatory parameters. They have to be supplied when your custom attribute is being used. Public constructor of your attribute class should accept these mandatory parameters as input.

o Named: Named Parameters are optional. You can pass them when using the attribute or you can leave them unspecified.


• Data type of your attribute parameter should be one among the following: bool, byte, char, short, int, long, float, double, string, enums, System.Type. It can also be an object or a single dimensional array whose type is one among the data type mentioned above.

• Once you have created attribute class with parameters defined, you can use the attribute wherever appropriate. When using or specifying value for the attribute, you have option to specify one value for the attribute or multiple values for the same attribute. By default, you can specify one value for the attribute. If you want to specify multiple values for the same attribute, set AllowMultiple to true in AttributeUsage as shown below:

[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)]

• Once the attribute value is set, you can retrieve it using reflection mechanism at run time.

Given below are code samples for custom attribute creation and usage:

Code for Attribute Class Creation:

Using System;

[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]

public class sampleCustomAttribute : System.Attribute {
public readonly string samplePosParam;
public string sampleNamedParam;

public sampleCustomAttribute(string samplePosParam) {
this.samplePosParam = samplePosParam;
sampleNamedParam = “sampleValue”;
}
}

In this example you have created a custom attribute called sampleCustomAttribute derived from System.Attribute. This attribute class is accessible to all programming objects and multiple values can be given to the attribute. This definition is done using AttributeUsage. This class has positional parameter called samplePosParam that is passed in the constructor. It also has a named parameter called sampleNamedParam.

Code for Custom Attribute Usage:


[sampleCustomAttribute("posParam1", sampleNamedParam = “test value”)]
[sampleCustomAttribute("posParam2")]
class SampleAttrUsageClass {
//Write your class specific code
}

In this cocde sample you are using sampleCustomAttribute and defining values to it. Since it can accept multiple values, two different values are supplied to the attribute, first line containing values for both positional and named parameter. Second line has supplied only the positional parameter value. Both are legal because named parameter is optional. Note that positional parameter value is directly mentioned whereas named parameter value is mentioned as:
sampleNamedParam = “test value”

Both the name of the named parameter and its value has to be mentioned.

Code for Retrieving Custom Attribute Value:

class AttrRetrivalClass {
public static void Main() {
System.Reflection.MemberInfo info = typeof(SampleAttrUsageClass);
object[] cusAttributes = info.GetCustomAttributes(true);
System.Console.WriteLine(“The Custom Attributes Stored are listed below:”);
for (int index = 0; index < cusAttributes.Length; index ++) {
System.Console.WriteLine(cusAttributes[index]);
}
}
}


With this piece of code, you can list down all custom attributes used by SampleAttrUsageClass. This is achieved using System.Reflection.MemberInfo.

|Designing applications in .Net using Service Oriented Architecture | How to Create and Use Anonymous Delegates in C# (C Sharp) |How to Define Custom Attributes in C# (C Sharp)| How To Handle Errors While Developing ASP.NET Applications | How to Use Indexer in Classes and Interfaces of C# (C Sharp)| Illustration of Access Keywords (base, this) with Examples in C# (C Sharp) | Illustration of Null Coalesce Operator (??) in C# (C Sharp) |Indexers Vs Properties in C# (C Sharp) | More about Reserved Attributes of C# (C Sharp)| Overview of Unified Type System of C# (C Sharp) | Purpose of Delegates in C# (C Sharp) |How does Simple Object Access Protocol (SOAP) help in Internet Communication |How to Create and Use Anonymous Delegates in C# (C Sharp)|

 


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.