Wednesday 30 October 2013

Properties in asp.net and their uses

Properties and their uses 

Properties get and set values. The C# language provides them as a convenient way to simplify syntax. They are implemented as methods .They act as the standard way of conversation with the class. We should always work by implementing properties. Because this also increases encapsulation.

Encapsulate means to hide. Encapsulation is also called data hiding.We can think Encapsulation like a capsule (medicine tablet) which hides medicine inside it. Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used for hide the code and data in a single unit to protect the data from outside world .Properties are the best method to encapsulate our data . With properties , our user of the class will be interacting with our class by means of our properties only.

These are different from fields(variables) as these will not require any memory to store data but these will point to the variable values .


Given below is an example to demonstrate the use of properties :

using System;
class MyClass
{
    int _myProperty;
    public int VariableValue
    {
       get
       {
         return this._myProperty;
       }
       set
       {
         this._myProperty= value;
       }
    }
}

class MainClass
{
    static void Main()
    {
      MyClass obj = new MyClass();
      obj.VariableValue = 1000; // setting the property value
      Console.WriteLine(obj.VariableValue); 
        // getting the property value 
    }
}
Result  : 1000
Properties can be of other data types also . For example : Boolean, string etc. 
Run the  code and enjoy object oriented programming by using properties .

Happy Coding!

No comments:

Post a Comment