C# attribute

In C#, an attribute is a special kind of class that provides additional information about a type or member of a type. Attributes are used to add metadata to code elements, such as classes, methods, and properties, which can then be accessed at runtime using reflection.

Attributes are defined using the [attributeName] syntax, where attributeName is the name of the attribute. Attributes can also have parameters, which can be specified using parentheses after the attribute name.

Here is an example of defining and using a custom attribute:

refer to‮i:‬giftidea.com
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class AuthorAttribute : Attribute
{
    public string Name { get; }

    public AuthorAttribute(string name)
    {
        Name = name;
    }
}

public class MyClass
{
    [Author("John Doe")]
    public void MyMethod()
    {
        // Method code here
    }
}

In this example, we have defined a custom attribute called AuthorAttribute that takes a string parameter name. The attribute is then applied to a method MyMethod in the MyClass class. The AttributeUsage attribute is also used to specify that the AuthorAttribute can only be applied to methods and cannot be applied multiple times to the same method.

To access the attribute at runtime, we can use reflection:

MyClass myClass = new MyClass();
MethodInfo methodInfo = typeof(MyClass).GetMethod("MyMethod");
AuthorAttribute attribute = (AuthorAttribute)methodInfo.GetCustomAttribute(typeof(AuthorAttribute));
Console.WriteLine(attribute.Name); // Output: John Doe

In this example, we create an instance of the MyClass class and retrieve the MyMethod method using reflection. We then use the GetCustomAttribute method to retrieve the AuthorAttribute applied to the method and access its Name property.

C# also provides a number of built-in attributes, such as the ObsoleteAttribute, which can be used to mark types and members that are no longer recommended for use. Other built-in attributes include SerializableAttribute, DllImportAttribute, and ConditionalAttribute, among others.