Why can't attribute parameters be dynamic?  
Author Message
Michiel1978





PostPosted: Visual C# General, Why can't attribute parameters be dynamic? Top

I was looking at decorating a method with the PrincipalPermission attribute. It tried to do this:

protected static string foo = "bar";

[PrincipalPermission(SecurityAction.Demand, Role = foo)]
public void DoSomething() { }

But it doesn't compile: "An attribute argument must be a constant expression, typeof expression or array creation expression"

What the technical reason for this and do you think it would be good feature to have this, or better to leave it as it is

I would be very interested in hearing your opinions on this, thanks!


Visual C#2  
 
 
Justin_H





PostPosted: Visual C# General, Why can't attribute parameters be dynamic? Top

I you think of Attributes as comments that compile I think you will see why this is not allowed.


 
 
James Curran





PostPosted: Visual C# General, Why can't attribute parameters be dynamic? Top

The value of the attributes paramters must be fixed at compile time. In your example, "foo" can change at run-time.

If you change the line to

protected const string foo= "bar";

it may work.



 
 
Michiel1978





PostPosted: Visual C# General, Why can't attribute parameters be dynamic? Top

Ok thanks for the explanation!

 
 
Stricneen





PostPosted: Visual C# General, Why can't attribute parameters be dynamic? Top

Some are dynamic - De****Display for instance

http://www.hide-link.com/


 
 
Tergiver





PostPosted: Visual C# General, Why can't attribute parameters be dynamic? Top

De****DisplayAttribute, like every other attribute, cannot take parameters at runtime. They must be compile-time constants.

De****DisplayAttribute takes a const string value. Sure it parses the string at runtime and through reflection works out what you wanted it to, but that doesn't change the fact that the attribute parameter cannot be dynamic.


 
 
Stricneen





PostPosted: Visual C# General, Why can't attribute parameters be dynamic? Top

My bad Sad