Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 315
string QNA Avatar asked Jun 02 '14 21:06

string QNA


1 Answers

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.

like image 103
Farhad Alizadeh Noori Avatar answered Oct 06 '22 18:10

Farhad Alizadeh Noori