How to access private variables using { get; set; }

Krowar picture Krowar · Jan 23, 2014 · Viewed 30.4k times · Source

I'd like to create a class for my website with a lot of private variable.

I thought there was a solution not to write all the getters and setters for each variable, something like

private int confirmed { get; set; }

Is it the right way? ANd then, how do I access this value from outside the class?

I've tried .confirmed , I get the error saying that it's private (which I understand)

But more surprising, .getConfirmed() or getconfirmed() do not work either.

I thought that the { get; set; } would create implicitely those methods.

Can someone clarify this concern for me please?

Answer

CodingIntrigue picture CodingIntrigue · Jan 23, 2014

You can declare your property as public, then mark the getter or setter individually as private:

public int confirmed { get; private set; }

That way, you can access confirmed outside of your defined class:

Console.WriteLine(myClass.confirmed); // This is OK
myClass.confirmed = "Nothing"; // Can't do this

And the only one who can set the value of confirmed is then MyClass:

public class MyClass {
    public int confirmed { get; private set; }

    public MyClass() {
        this.confirmed = "This"; // This is fine as we have private access
    }
}