Reputation: 610
I was trying to write the following code -
[Range(DateTime.UtcNow.Add(-7).Ticks, DateTime.UtcNow.Add(7).Ticks)]
public DateTime TimeStamp;
The compiler reported the error - An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.
The error is self descriptive, it is okay. My question is - what is the rationale to not allow expressions / variables / method calls as argument for any Attribute in C#?
Upvotes: 0
Views: 433
Reputation: 101681
Because attributes are stored as metadata, their values should be known at compile time so they can be stored after the code is compiled and don't change at runtime.
Upvotes: 2