C# – How get and set accessors work

cobject-orientedvb.net

The standard method of implementing get and set accessors in C# and VB.NET is to use a public property to set and retrieve the value of a corresponding private variable. Am I right in saying that this has no effect of different instances of a variable? By this I mean, if there are different instantiations of an object, then those instances and their properties are completely independent right? So I think my understanding is correct that setting a private variable is just a construct to be able to implement the get and set pattern? Never been 100% sure about this.

Best Answer

You are correct up to this question:

So I think my understanding is correct that setting a private variable is just a construct to be able to implement the get and set pattern?

Quite the opposite is true. Ideally, only the encapsulating object should have direct access to the object(s) it encapsulates. This is known as the Law of Demeter.

In reality, following this "law" (like most programming laws) religiously can lead to over-engineering, but it is a very good principle to bear in mind.

Make the mental shift so you have to justify the existence of a getter, and separately a setter, before you blindly implement them for all private fields.