How to get common name of parameter type at compile time?

I am trying to implement a generic class. It should have a property with an attribute that accepts a compile-time constant that I want to set as the name of the parameter type. Something like that:

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 since typeof(T).Name is evaluated at runtime, it does not work. Is it possible?

+7
generics reflection c # compile-time compile-time-constant
source share
1 answer

I don't think this is the correct way to use attributes. Attributes for adding specific characteristics to a class. These are tags that you add to classes at compile time for query and use at runtime. Are you trying to add an attribute at runtime and use it like? Why do you want to use attributes to store information available at runtime?

The type name can be easily requested at runtime. I think you should provide more information about what exactly you want to achieve, otherwise I think that using the TypeName property is probably pretty good.

+1
source share

All Articles