I want to default value(getter value) to be set for the data property , if the value set by the user does not meet the condition(without private variables).
Here is the code
public class TreeViewModel{
public a()
{
this.Height = 200;
}
public int Height { get; set ; }
}
If the user sets the value of height lesser that 200 , I want the default value(200) to be set. I tried the following code but not successful as I need to define a body for get (coding in c# MVC)
public int Height { get; set {if (value < 200)
value = 200;
} }
Shouldn't it be:
public class TreeViewModel
{
private const int minHeight = 200;
private int _Height = minHeight;
public int Height
{
get { return _Height; }
set { this._Height = value < minHeight ? minHeight : value; }
}
}
You may also think of defining the minHeight value externally, e.g. in a config file.
Oh, and yes I used a private variable - the property has no internal way to store a value, so the only other alternative would be to use another persistance medium e.g. Session, ViewState, DataBase etc.
Automatic properties will create a backing field for you under the covers:
public int Height { get; set; }
gets turned into:
public int Height
{
[CompilerGenerated]
get
{
return this.k__BackingField;
}
[CompilerGenerated]
set
{
this.k__BackingField = value;
}
}
So you'll be fine creating a backing field of your own:
public class TreeViewModel {
private const int heightDefault = 200;
private int height = heightDefault;
public int Height {
get {
return this.height;
}
set {
this.height = (value < heightDefault ) ? heightDefault : value;
}
}
}
When you use automatic properties, you don't have access to the internal variable itself, so you can't put any logic in there.
You will have to go for a private variable and write the accessors by hand, as pointed out by James.
Automatic properties should be used only when no additional logic is required which is not your case. You'll have to add a backing field. I guess that if you'll search hard enough you'll find some twisted way to do it without a backing field but I would keep it simple and use the old style for the sake of clarity.