I'm trying to implement a generic class. It should have a property with an attribute that takes a compile-time constant, which I want to set as the parameter type's name. Something like this:
namespace Example
{
public class MyGeneric<T>
{
[SomeAttribute(CompileTimeConstant)]
public int MyProperty { get; set; }
private const string CompileTimeConstant = typeof(T).Name; // error CS0133:
// The expression being assigned to `Example.MyGeneric<T>.CompileTimeConstant' must be constant
}
}
But because typeof(T).Name
is evaluated at run-time, it doesn't work. Is it possible?
I don't think this is the right way of using attributes. Attributes are there to add specific characteristics to a class. They are tags you add to classes at compile time to be queried and used in run time. You are trying to add an attribute at runtime and use it how? Why do you want to use attributes to hold information available in runtime?
The type's name can easily be queried at runtime. I think you should provide more information on what exactly you want to achieve otherwise I think using a TypeName
property is probably good enough.
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