Can method attributes be changed at runtime?

  • Thread starter Thread starter Ray Stevens
  • Start date Start date
R

Ray Stevens

I have a generated class that is using method attributes to discover the
proper server. Because we have development, staging, prod servers I prefer
to not generate a new class every time we do a promotion but, rather, pass
this in through the environment-specific config file.

Is this possible?
 
Ray,

Through attributes, no, it is not possible. Attributes are written at
compile time into the metadata of the assembly for whatever they are
attached to.

You are better off creating a custom configuration section in your
..config file for the app, and just reading the information from there (since
it is subject to change outside of the times you compile the app).

Hope this helps.
 
Ray,
it is not like there is no way. You can implement ICustomTypeDescriptor
interface in you class.

You need to implement ICustomTypeDescriptor.GetAttributes method and return
the dynamic set of attributes. The rest of the methods you can delegate to
the TypeDescriptor class.
In order this to work you need use TypeDescriptor to get the type
attributes. If you use the Type object for the type, as the others said
there is no way to alter the attributes collection. The PropertyGrid, visual
designers they all use the TypeDesciptor so this approach should work there.
I haven't use this for custom attributes, but have used it for other things
and it works.

One more thing... TypeDescriptor caches all type information so you need to
call TypeDescriptor.Refresh method if you change attribute collection.

HTH
Stoitcho Goutsev (100) [C# MVP]
 
Back
Top