While attributes can take parameters, they could not previously take generic type arguments. This meant that either typed versions of attributes had to be created or the attribute had to take an object and validate the type was acceptable at runtime.
Code
C#
public class DataAttribute<T> : Attribute
{
public DataAttribute(T data)
{
}
}
[Data<string>("Hello")]
[Data<int>(123)]
public void DoSomething()
{
// ...
}
C#
public class StringDataAttribute : Attribute
{
public StringDataAttribute(string data)
{
}
}
public class IntDataAttribute : Attribute
{
public IntDataAttribute(int data)
{
}
}
[StringData("Hello")]
[IntData(123)]
public void DoSomething()
{
// ...
}
Notes
- Type parameters are limited to the same subset that
typeof
supports. You can not use:dynamic
- nullable reference types like
string?
- tuple types like
(int, int)