C# tutorials > Modern C# Features > C# 6.0 and Later > What are generic attributes?
What are generic attributes?
Basic Generic Attribute Declaration
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class GenericTypeAttribute<T> : Attribute
{
public GenericTypeAttribute()
{
Console.WriteLine($"Attribute applied with type: {typeof(T).Name}");
}
}
[GenericType<int>]
public class MyClass
{
// Class implementation
}
[GenericType<string>]
public struct MyStruct
{
// Struct implementation
}
Using Properties in Generic Attributes
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class GenericPropertyAttribute<T> : Attribute
{
public T Value { get; set; }
public GenericPropertyAttribute(T value)
{
Value = value;
Console.WriteLine($"Attribute applied with value: {Value}");
}
}
[GenericProperty<int>(123)]
public class AnotherClass
{
// Class implementation
}
[GenericProperty<string>("Hello, Generic Attribute!")]
public struct AnotherStruct
{
// Struct implementation
}
Retrieving Generic Attributes at Runtime (Reflection)
using System;
using System.Reflection;
public class Program
{
public static void Main(string[] args)
{
Type type = typeof(MyClass);
var attribute = type.GetCustomAttribute<GenericTypeAttribute<int>>();
if (attribute != null)
{
Console.WriteLine("GenericTypeAttribute<int> found on MyClass.");
}
Type type2 = typeof(AnotherClass);
var attribute2 = type2.GetCustomAttribute<GenericPropertyAttribute<int>>();
if (attribute2 != null)
{
Console.WriteLine($"GenericPropertyAttribute<int> found on AnotherClass with value: {attribute2.Value}.");
}
}
}
Concepts Behind the Snippet
Real-Life Use Case Section
Best Practices
Interview Tip
When to use them
Memory footprint
Alternatives
The best approach depends on the specific requirements of your application.
Pros
Cons
FAQ
-
Can I use generic attributes on generic methods?
Yes, you can use generic attributes on generic methods. The type parameters of the method and the attribute do not have to be the same, but they should be used to convey information about the method's behavior or characteristics related to the type parameters. -
Are there any limitations on the types I can use as type parameters in generic attributes?
Generally, there are no specific limitations on the types you can use as type parameters. However, the types you use should be meaningful and relevant to the purpose of the attribute. Primitive types, classes, structs, interfaces, and even other generic types can all be used. -
Can I have multiple generic type parameters in an attribute?
Yes, you can have multiple generic type parameters in an attribute. For example:public class MyAttribute
This allows you to create more complex and flexible attributes that can work with multiple types simultaneously.: Attribute { ... }