Why we need Properties in C#

Solution 1:

Short answer: Encapsulation

Long answer: Properties are very versitile. It allows you to choose how you want to expose your data to outside objects. You can inject some amount of data validation when setting values. It also aliviates the headache of getX() and setX() methods seen in the likes of Java, etc.

Solution 2:

Think about it : You have a room for which you want to regulate who can come in to keep the internal consistency and security of that room as you would not want anyone to come in and mess it up and leave it like nothing happened. So that room would be your instantiated class and properties would be the doors people come use to get into the room. You make proper checks in the setters and getters of your properties to make sure any unexpected things come in and leave.

More technical answer would be encapsulation and you can check this answer to get more information on that: https://stackoverflow.com/a/1523556/44852

class Room {
   public string sectionOne;
   public string sectionTwo;
}

Room r = new Room();
r.sectionOne = "enter";

People is getting in to sectionOne pretty easily, there wasn't any checking.

class Room 
{
   private string sectionOne;
   private string sectionTwo;

   public string SectionOne 
   {
      get 
      {
        return sectionOne; 
      }
      set 
      { 
        sectionOne = Check(value); 
      }
   }
}

Room r = new Room();
r.SectionOne = "enter";

now you checked the person and know about whether he has something evil with him.

Solution 3:

Lots of reasons:

  • Semantics. Properties separate the implementation of your type from the interface.
  • Binary Compatibility. If you ever need to change a property, you can do so without breaking binary compatibility for dependent code. With fields, you have to recompile everything even if the new implementation uses a property with the same name.
  • Databinding. You can't databind to a field.