Property is a member that provides the mechanism to what gets assigned and what gets returned from your fields/classes variables. In simple terms we can say that properties help us to inject the logic inside the fields /classes variables. By using the Access modifiers we can make it possible to what gets assigned and what gets returned from your fields. Properties implements Encapsulation because it hides the complexity from the User.

Why Properties:
- As discussed earlier if we make our class fields public we will not have any control on what gets assigned and what gets returned from your fields.
- The following are the scenarios which we face when our fields are public.
The following is a class called Employee Class with public fields ID:
- Our Business rule say that ID should not be less than 1.
- Name cannot be set to NULL.
- Marks Should be Read only
But as we can see in the following code snippet we are able to change the values and assigned the same to our fields.
- public class Employee
- {
- public int ID;
- }
- public class Program
- {
- static void Main(string[] args)
- {
- Employee obj = new Employee ();
- obj.ID = -100; // ID should not be less than 1
- obj.NAME = null; // name should not be empty
- obj.MARKS = 20; //Marks should be a read only property but here we are able to change it
- Console.WriteLine("the values of the new object are ID {0}", obj.ID);
- Console.ReadLine();
- }
- }

So in order to validate the Business rule we use get and set methods properties in C#. The programming language that before properties they use Getter and Setter (for better understanding) method as in the following:
- Firstly, we create our property to be private so that they won’t be accessible to the external world.
- Now we write to methods for set and get i.e. SetId, GetId to control what get into the fields and what set into the fields of class.






















Santhakumar MunuswamyPosted Oct 5, 2015, 11:54 PM
Nice Share
Nilesh JadavPosted Oct 4, 2015, 8:48 PM
Good one on Properties
Saillesh PawarPosted Oct 4, 2015, 2:37 PM
Thanks Vinodh
Vinodh NarayananPosted Oct 4, 2015, 2:02 PM
nice share