1

Is there a way around to pass non-constant complex or primitive values to an attribute?

public class SomeClass
{
     private SomeOtherClass _someOtherClass = new SomeOtherClass();
     private int _somePrimitiveVariable = CalculateSomeValue();

     [MyAttribute(InputValue = _someOtherClass)
     public void MyMethod()
     {
         //Some stuff
     }
     //Or can it be like this?
     [MyAttribute(InputValue = _somePrimitiveVariable)
     public void MyMethod()
     {
         //Some stuff
     }
}
E-A
  • 1,995
  • 6
  • 33
  • 47
  • I guess you can't. Have a look at a similar post here: http://stackoverflow.com/questions/1235617/how-to-pass-objects-into-an-attribute-constructor – kelsier Apr 17 '14 at 07:34

1 Answers1

1

Attributes are resolved at compile time, so the comments saying "no" are mostly correct.

However, if you can't rework your design, there are limited workarounds. If this is a universal property you wish to set (that will apply to every user of the attribute), your best bet might be having an initializer method in your code call a configuration method on the attribute. This would look vaguely similar to Can C# Attributes access the Target Class?. Ugly, but might work in specific circumstances.

Zaccone
  • 145
  • 4
  • This is an interesting approach.. I'm now working on this concept. – E-A Apr 17 '14 at 07:42
  • I can't deny your help. I did it up to a some point with your approach. But eventually, because of the substructure I had to do it by a HttpContext session object. But still, your approach did helped. Thank you. – E-A Apr 20 '14 at 08:17