Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KeyurRamoliya/9dd169c1fd82d5a2c00c8f53f27281b0 to your computer and use it in GitHub Desktop.
Save KeyurRamoliya/9dd169c1fd82d5a2c00c8f53f27281b0 to your computer and use it in GitHub Desktop.
Custom Attributes for Metadata and Reflection

Custom Attributes for Metadata and Reflection

Custom attributes in C# allow you to attach metadata to types, methods, properties, and other code elements. You can then use reflection to inspect this metadata at runtime. This is especially useful for scenarios like code analysis, serialization, or custom behaviors based on metadata.

Consider the below example, we define a custom attribute MyCustomAttribute, and apply it to a class and a method. Then, we use reflection to retrieve and inspect these attributes at runtime.

Custom attributes can be used for various purposes, such as defining validation rules, serialization instructions, or custom documentation. They are commonly used in libraries and frameworks to extend the functionality of code based on metadata.

using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
    public string Description { get; }

    public MyCustomAttribute(string description)
    {
        Description = description;
    }
}

[MyCustom("This is a sample class.")]
public class SampleClass
{
    [MyCustom("This is a sample method.")]
    public void SampleMethod()
    {
        // Method implementation
    }
}

public class Program
{
    public static void Main()
    {
        // Get attributes on class
        var classAttributes = typeof(SampleClass).GetCustomAttributes(typeof(MyCustomAttribute), false);
        if (classAttributes.Length > 0)
        {
            var attribute = (MyCustomAttribute)classAttributes[0];
            Console.WriteLine($"Class Description: {attribute.Description}");
        }

        // Get attributes on method
        var methodAttributes = typeof(SampleClass).GetMethod("SampleMethod").GetCustomAttributes(typeof(MyCustomAttribute), false);
        if (methodAttributes.Length > 0)
        {
            var attribute = (MyCustomAttribute)methodAttributes[0];
            Console.WriteLine($"Method Description: {attribute.Description}");
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment