In C#, by default all the properties defined in a class are always public.Properties get and set values. The C# language provides them as a convenient way to simplify syntax. They are implemented as methods in the intermediate language. They are standard access points to a class from external code.
Eg:
public class clsMyClass
{
public string myproperty1{get; set;}
}
is an example of a automatic property type available in C#.
Now the 'Question' arises what are major benefits of using Properties in C# over Public variables.
* Public variables are unsafe as everyone can set any value and you have no control over them, while in case of property you can put a check that no one could set invalid value to them.
* Using Properties we can restrict any one, that means he/she can only get the value or read the value but could not set the value from outside of class and vice- a- versa.
* You can not debug with public variables but you can do that with property.
* A variable/field is an implementation and by exposing it directly you are 'breaking encapsulation'.The object now has no way to know its state has changed and that's a bad thing.
* 'Databinding' doesn't acknowledge fields at all, it will only work with properties.
* Properties do not have to refer to an 'actual variable'.
Eg:
public class clsExample
{
private int _num1;
private int _num2;
public int Sum
{get{return _num1+_num2};}
}
* A property can be a interface member while a variable can't be a member.
* A variable can be passed by reference while a property can't be.
* A variable has only one access modifier while a property have different modifiers on get and set.