9

I have a class decorated with a attribute ...[DataEntity("MESSAGE_STAGING", EnableCaching = true, CacheTimeout = 43200)]

for some requirement,I want to change this value MESSAGE_STAGING at run time to Test_Message_Staging.

What is the best possible way to achieve this?

Can I use reflection, or is there any other way to do this.

Please provide code samples.

Thanks SNA

Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47
SNA
  • 7,528
  • 12
  • 44
  • 60

3 Answers3

9

I don't believe it's possible to set attributes using reflection - and even if it is, I'd encourage you not to do so.

Attributes should be used for metadata which is known at compile-time. If you want a more dynamic form of metadata, load it from a file or use app.config instead... or at least have some special "placeholder" values (like |DataDirectory| in a connection string) which can be resolved at execution time.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • the requirement is i hav to change the table name some way.Attribute will not allow taking values from web.config.The parameter should be a constant. so the only idea i can think of is get the attribute(dataEntity) of the class from reflection and change its property.But is it possible – SNA Jan 29 '10 at 07:39
5

It's not possible to change attribute property value at run-time with reflection because attributes are meta-data serialized in the assembly and changing them means changing the assembly.

Branislav Abadjimarinov
  • 5,101
  • 3
  • 35
  • 44
  • Reflection is a general mechanism available to all types because its foundation is established in the GetType method of the root Object class. The information it returns for a type is not extensible, in that it cannot be modified after compilation of the target type. – Branislav Abadjimarinov Jan 29 '10 at 12:23
1

If i understand you correctly, there is a possible way in reflection to change the attribute value of a instance at runtime.. checkout the sample code

        AttributeCollection ac  = TypeDescriptor.GetAttributes(yourObj);

        foreach (var att in ac)
        {
            //DataEntityAttribute  -- ur attribute class name
            DataEntityAttribute da = att as DataEntityAttribute ;
            Console.WriteLine(da.field1);  //initially it shows MESSAGE_STAGING
            da.field1= "Test_Message_Staging";  
         }


         //Check the changed value
        AttributeCollection acc = TypeDescriptor.GetAttributes(yourObj);

        foreach (var att in ac)
        {
            DataEntityAttribute da = att as DataEntityAttribute ;
            Console.WriteLine(da.field1); //now it shows Test_Message_Staging
        }
RameshVel
  • 64,778
  • 30
  • 169
  • 213