Given an example such as ..
public interface IInterface { }
public static void Insert<T>(this IList<T> list, IList<T> items) where T : IInterface
{
// ... logic
}
This works fine, but I was wondering if it is possible to use an Attribute as a constraint. Such as ...
class InsertableAttribute : Attribute
public static void Insert<T>(this IList<T> list, IList<T> items) where T : [Insertable]
{
// ... logic
}
Obviously this syntax doesn't work, or I wouldn't be posting the question. But I'm just curious if it is possible or not, and how to do it.
Attributes can be applied to generic types in the same way as non-generic types.
You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.
There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.
Value type constraint If we declare the generic class using the following code then we will get a compile-time error if we try to substitute a reference type for the type parameter.
No. You can only use (base)classes and interfaces as constraints.
You can however do something like this:
public static void Insert<T>(this IList<T> list, IList<T> items)
{
var attributes = typeof(T).GetCustomAttributes(typeof(InsertableAttribute), true);
if (attributes.Length == 0)
throw new ArgumentException("T does not have attribute InsertableAttribute");
/// Logic.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With