16 November

C# 11 – Generic on attributes

Programming

min. read

Reading Time: < 1 minute
C# 11
C# 11

Let’s list all the features that C# 11 brings to the table. Let’s discuss them all one by one, with their use cases, and see how they can come in handy. At the bottom of each article, you can find a link to all 14 new C# features!

Generic on attributes

This feature was supposed to come out with C# 10, but it was postponed to C# 11.

Now instead of creating attributes that take typeof parameters, we can use a generic type to describe them.

Old ways

[Filter(typeof(MyFilterType))]
public class SomeClass {...}

public class FilterAttribute : Attribute
{
    public Type FilterType { get; set; }

    public FilterAttribute(Type filterType)
    {
         if(!typeof(IFilterType).IsAssignableFrom(filterType))
             throw new Exception("Runtime exception");
         ...
    }
}

Generic Attribute

public interface IFilterType {}

public class FilterAttribute<TFilterType> : Attribute where TFilterType : IFilterType 
{
    public Type FilterType { get; set; }

    public FilterAttribute()
    {
         FilterType = typeof(TFilterType);
    }
}

[Filter<MyFilterType>)]  // OK
public class SomeClass {...}

[Filter<SomethingElse>)]  // Build time exception!!!
public class SomeOtherClass {...}

With this, now you can limit what you can pass into the attribute. And make sure that we only provide what should be provided. This also has the benefit of code-completion now showing proper types to put into the generic.

Further reading at dotnet GitHub page.

Current article:
Generic on attributes


Let's talk

SEND THE EMAIL

I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.

I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.