Reputation: 6483
I have a set of properties and need to provide a default values for them. Sure I can do the following in getter:
public string MyProp {
get {
if(!string.IsNulOrEmpty(_myProp))
return _myProp;
else
return "Default";
}
But I`d like it to look like
[DefaultValue("Default")]
public string Processes
{
get { return _processes; }
Is there a good way to do it with attributes? I`ve spent some time to look for some attribute or a way to do this but found nothing.
Upvotes: 0
Views: 465
Reputation: 42516
You can't do this with attributes unless you use some sort of post-processor like PostSharp. The DefaultValueAttribute is used to inform the PropertyGrid (or other property browser type controls) of what the default value of the property should be so they can indicate when it has been changed from that default and reset it back to that default.
What you should do is something like this:
private const string _processDefault = "Default";
private string _processDefault = _processDefault Default;
public string Process
{
get
{
return _processDefault ;
}
set
{
if (String.IsNullOrEmpty(value))
{
value = _processDefault ;
}
_myProp = value;
}
}
If you don't want the value to be set outside of your control make the setter private.
Using this approach you could still use the attribute, but would need to write some reflection code to get it's value and you would need to initialize the private _myProp
variable through a function call rather than inline like I've shown.
Upvotes: 0
Reputation: 55062
I'd do:
private string processes = "default";
public string Processes
{
...
}
Upvotes: 2