Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 499
Krowar Avatar asked Jan 23 '14 15:01

Krowar


1 Answers

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
    }
}
like image 145
CodingIntrigue Avatar answered Sep 19 '22 00:09

CodingIntrigue