I’m trying to make the DefaultValueAttribute value dynamic, and this is how I’m attempting to accomplish this
DefaultValueAttribute(string.Format("Copyright @ 2009 - {0} {1}", DateTime.Now.Year.ToString(), "Gods Creation Taxidermy"))]
Doing so gives me this error message:
An attribute argument must be a constant expression, typeof expression
or array creation expression of an attribute parameter type
Is what I’m trying to do just not possible or am I going about it wrong? Any suggestons or ideas?
EDIT: Here’s the entire property:
[CategoryAttribute("Text Settings"),
DescriptionAttribute("Copyright Text..."),
DefaultValueAttribute(string.Format("Copyright @ 2009 - {0} {1}", DateTime.Now.Year.ToString(), "Gods Creation Taxidermy"))]
public string CopyrightText { get; set; }
Most often, the way attributes are used will prevent this. Only a pure literal constant value, which can be understood before compiling really gets underway, can be used in a declarative attribute constructor. Basically only pure numbers, strings, types or enums, with no manipulation.
The exception to this is when the module that is looking at the attributes is compatible with ICustomTypeDescriptor.
A type that implements ICustomTypeDescriptor can use the GetAttributes method to return a set of attributes created entirely at runtime. This means that not only the state but also the presence of an attribute can be controlled at runtime by the state of your object.
A reminder though: the limitation of this is approach is that not everything that is attribute-driven looks for this interface. In fact, many don’t. But it may be worth looking into. One example of a module that does make use of ICustomTypeDescriptor is the PropertyGrid control. The use of these together is described here: http://www.codeproject.com/KB/miscctrl/bending_property.aspx