-1

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; }
PsychoCoder
  • 10,570
  • 12
  • 44
  • 60

2 Answers2

1

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

Community
  • 1
  • 1
Chris Ammerman
  • 14,978
  • 8
  • 41
  • 41
  • It would be nice if this would work, sure would come in handy, but thanks for the time you put into this for me. – PsychoCoder Dec 07 '11 at 18:45
0

This is not possible.

As the error clearly states, attribute paramters must be compile-time constants.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964