Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic Property Values and Defaults [duplicate]

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"; } }
}
like image 418
Joseph Le Brech Avatar asked Aug 15 '11 10:08

Joseph Le Brech


3 Answers

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;} 
}
like image 147
Lee Smith Avatar answered Sep 26 '22 02:09

Lee Smith


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; }
}
like image 44
Guffa Avatar answered Sep 24 '22 02:09

Guffa


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;} 
}
like image 38
Jethro Avatar answered Sep 22 '22 02:09

Jethro