Alan2
Alan2

Reputation: 24602

Is there a way that I can set the default values of fields in a class so I don't have to specify a value on creation?

I have this class:

public class ParamViewModel: BaseViewModel
{
    int _id;
    public int Id
    {
        get => _id;
        set => SetProperty(ref _id, value);
    }

    string _name;
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    bool _isSelected;
    public bool IsSelected
    {
        get => _isSelected;
        set => SetProperty(ref _isSelected, value);
    }

}

public ParamViewModel[] STIVM { get; set; } = new[] {
        new ParamViewModel{  Id = 0, Name = STI.Zero.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 1, Name = STI.ZeroFive.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 2, Name = STI.One.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 3, Name = STI.OneFive.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 4, Name = STI.Two.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 5, Name = STI.Three.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 6, Name = STI.Four.Text(), IsSelected = false} ,
    };

Is there a way that IsSelected could be false by default?

Upvotes: 0

Views: 46

Answers (4)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37115

Sure, by setting _isSelected to false on its declaration:

bool _isSelected = false;

In fact you could achieve the exact same when setting that value within the constructor of your class, as vc 74 pointed out.

However that is pointless, as false already is the default-value for bool.

Thus let´s see how it works for the int-property which should default to -1 instead of the "normal" default of zero:

int _id = -1;
public int Id
{
    get => _id;
    set => SetProperty(ref _id, value);
}

Upvotes: 3

vc 74
vc 74

Reputation: 38179

I think you actually mean call the property setter on construction:

public ParamViewModel()
{
    IsSelected = false;
}

Upvotes: 1

Yogesh Patel
Yogesh Patel

Reputation: 838

Declare _isSelected variable with false.

bool _isSelected = false;

Upvotes: 0

Andrew
Andrew

Reputation: 61

Change the isSelected to

bool _isSelected = false;

Upvotes: 0

Related Questions