16 November
C# 11 – Generic on attributes
Programming
min. read

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.
Author
About prog
Founded in 2016 in Warsaw, Poland. Prographers mission is to help the world put the sofware to work in new ways, through the delivery of custom tailored 3D and web applications to match the needs of the customers.
SIMILAR POSTS
First-class support for generic Attributes in C# 11
Programming
min. read
C# 11 – Everything you need to know
Programming
min. read
C# 11 – List patterns
Programming
min. read