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?

Recommended Answers

All 2 Replies

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.

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.

commented: +1 for the very first line of your post. Not many people understand this +11
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.