Possible Duplicate:
How do you give a C# Auto-Property a default value?
I have a property in a class like so
public String fontWeight { get; set; }
I want it's default to be of "Normal"
Is there a way to do this in "automatic" style rather than the following
public String fontWeight {
get { return fontWeight; }
set { if (value!=null) { fontWeight = value; } else { fontWeight = "Normal"; } }
}
Yes you can.
If your looking for something like:
[DefaultValue("Normal")]
public String FontWeight
{
get;
set;
}
Do a google search for 'Aspect Oriented Programming using .NET'
..if this is overkill for you do this:
private string fontWeight;
public String FontWeight {
get
{
return fontWeight ?? "Normal";
}
set {fontWeight = value;}
}
No, an automatic property is just a plain getter and/or setter and a backing variable. If you want to put any kind of logic in the property, you have to use the regular property syntax.
You can use the ??
operator to make it a bit shorter, though:
private string _fontWeight;
public String FontWeight {
get { return _fontWeight; }
set { _fontWeight = value ?? "Normal"; }
}
Note that the setter is not used to initialise the property, so if you don't set the value in the constructor (or assign a value in the variable declaration), the default value is still null. You could make the check in the getter instead to get around this:
private string _fontWeight;
public String FontWeight {
get { return _fontWeight ?? "Normal"; }
set { _fontWeight = value; }
}
You will need to use a backing field.
private string fontWeight;
public String FontWeight
{
get { String.IsNullOrEmpty(fontWeight) ? "Normal" : fontWeight;}
set {fontWeight = String.IsNullOrEmpty(value) ? "Normal" : value;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With