string QNA
string QNA

Reputation: 3210

How can I get a generic parameter type name at compile time?

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?

Upvotes: 9

Views: 1214

Answers (1)

Farhad Alizadeh Noori
Farhad Alizadeh Noori

Reputation: 2306

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.

Upvotes: 1

Related Questions