0

I know that assigning the access type 'private' to a variable is to prevent other methods from accessing and modifing that variable from out side its class.

I understand that the get and set modifiers are typically used to access private variables.

Why can a private variable be accessed by a get and set modifier if its supposed to be private? Isnt a private variable supposed to be protected from modification from outside its class?

Edited by iConqueror: er

3
Contributors
2
Replies
31
Views
2 Years
Discussion Span
Last Post by deceptikon
0

The field is private so you don't possibly mess it up.
You access it through get and set. In the property syntax you can validate the value you want to set for example.
Read this article for more info.

2

Why can a private variable be accessed by a get and set modifier if its supposed to be private? Isnt a private variable supposed to be protected from modification from outside its class?

A private member is supposed to be protected from uncontrolled modification. A property or method that exposes a private member typically does so in a controlled manner in well designed code.

I suspect in asking the question you're thinking of this:

private int foo;

public int Foo
{
    get { return foo; }
    set { foo = value; }
}

And that's not best practice because it's not much better than making foo public. The most you'll get out of it is future proofing for if you decide to tighten up access to foo (ie. the property is already there and only the set needs modification).

Of course, rather than making the private member public, an autoproperty is the better choice when you don't need controlled public access:

public int Foo { get; set; }

Though I've found more often that I favor this in the general case:

public int Foo { get; private set; }

Wherein Foo is set internally through another component of the public interface like a constructor or method.

Votes + Comments
+1 for the very first line of your post. Not many people understand this
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.