Home > Net >  get; set; vs get; private set;
get; set; vs get; private set;

Time:11-14

I am just wondering, functionally, what is the difference between:

private int var {get; set;}

and

public int var {get; private set;}

Also, why does

private int var {get; set;}

return an error?

I am new to using getters and setters.

CodePudding user response:

The main difference between the two is that

private int var {get; set;}

will not allow other classes to access and modify the value of var, while

public int var {get; private set;}

will only allow other classes to access the value of var, but not modify it.

The reason why

private int var {get; set;}

returns an error is because you are trying to set the value of var to a private field. In order to set the value of var, you need to use the public setter.

CodePudding user response:

public int var { get; set; } is like:

public class Var {
    private int var;

    public int Get() { return var; }
    public void Set(int var) { this.var = var; }
}

if you define public int var { get; private set; }, it will be like:

public class Var {
    private int var;

    public int Get() { return var; }
    private void Set(int var) { this.var = var; }
}

So getter and setter is like call Get() or Set() function when you get or set var:

Var v = new Var();

// like v.Set(1);
// if Set() is private, it will returns error.
v.var = 1;

// like Console.log(v.Get());
Console.log(v.var);

It just a analogy, maybe you could see about properties document to know more.

  • Related