Search code examples
c#propertiesencapsulationmember

Data encapsulation in C# using properties


currently I am thinking about data encapsulation in C# and I am a little bit confused. Years ago, when I started to learn programing with C++, my professor told me: - "Create a class and hide it data members, so it can't be manipulated directly from outside"

Example: You are parsing an XML file and store the parsed data into some data members inside the parser class.

Now, when I am looking at C#. You have there properties. This feature makes the internal state / internal data of a class visible to outside. There is no encapsulation anymore. Right?

private string _mystring;
public string MyString
{
  get {return _mystring;}
  set {_mystring = value;}
}

From my point of view there is no difference between making data members public or having public properties, which have getters and setters, where you pass your private data members through.

Can someone explaing me that please?

Thanks


Solution

  • The private data is encapsulated by the property itself. The only way to access the data is through the property.

    In your situation above, there is little reason to use the property. However, if you later need to add some validation, you can, without breaking the API, ie::

    private string _mystring;
    public string MyString
    {
      get {return _mystring;}
      set 
      {
          if (IsAcceptableInput(value))
             _mystring = value;
      }
    }
    

    Remember that a Property, in .NET, is really just a cleaner syntax for 2 methods - one method for the property get section, and one for the property set section. It provides all of the same encapsulation as a pair of methods in C++, but a (arguably) nicer syntax for usage.