9

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?

string QNA
  • 3,110
  • 3
  • 17
  • 14

1 Answers1

1

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.

Farhad Alizadeh Noori
  • 2,276
  • 17
  • 22
  • I wanted to use the `ConfigurationCollectionAttribute` to create `class ConfigurationSectionOfCollection where TConfigurationElement : ConfigurationElement` that will use a configuration collection with the name of `TConfigurationElement` as the collection's XML tag name. This way I don't have to copy the code of configuration collections and sections for each of the 5 times I use them. If I ever wanted to change one of those sections, its class could stop inheriting from `ConfigurationSectionOfCollection`. – string QNA Jun 21 '14 at 13:56