Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Attributes for Generic Constraints [duplicate]

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.

like image 289
Ciel Avatar asked Nov 10 '10 16:11

Ciel


People also ask

Can attributes be generic?

Attributes can be applied to generic types in the same way as non-generic types.

Can generic classes be constrained?

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.

Can a generic class have multiple constraints?

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.

Which of the following generic constraints restricts the generic type parameter to an object of the 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.


1 Answers

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.
}
like image 157
Pieter van Ginkel Avatar answered Sep 26 '22 06:09

Pieter van Ginkel