Wednesday, July 1, 2009

Properties in C#

Properties in C#

Why property are required?
If you are simply delcaring a variable and you want to do some operation on a variable .
E.g: Class demo1
{
Public string Age;
}
Class Maindemo1
{
demo1 Demo = new demo1();
Demo.Age= -35;
}

This we want to check manually whether the logic is correct or not.Like the below way

class Employee
{
public int Age;

public int GetAge()
{
return (Age);
}

public void SetAge(int value)
{
if(value<0)
throw new ArgumentOutOfRangeException ("Age Must be greater than zero");
Age = value;
}


}

class MainEmployee
{
static void Main()
{
Employee e = new Employee();
e.SetAge(35);
int i = e.GetAge();
}
}

This will solve the above problem.If Age is less than zero it will throw an error.
Disadvantage : want to write long number of codes.and user must call a method rather than a variable.

CLR offers a mechanism to overcome the above disadvantage,ie by using properties.
class Employee
{
private int _Age1;
public int Age1
{
get
{
return _Age1;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("Age Must be greater than zero");
_Age1 = value;
}
}
}

class MainEmployee
{
static void Main()
{
Employee e = new Employee();
e.Age1 = 35;
int j = e.Age1;
}
}

The CLR offers get accessor and set accessor.During compile time it will automatically added GetAge() and SetAge(int value).And makes the code easy

Types of Properties

1) Parameterless Property
2) Parameterful property


Parameterless Property

This doesn’t have a parameter
E.g :
public int Age1
{
get
{
return _Age1;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("Age Must be greater than zero");
_Age1 = value;
}
}
}

Parameterful property

C# developer to overload [] operator

private int[] arr=new int[10]
public int this[int i]
{
get
{
return arr[i];
}
set
{
arr[i]=value;
}
}

CLR doesnot differentiate parameterless properties and parameterful proprty.C# team set this[] as syntax for indexer.which this choice means is that C# allows indexer to be defined only instace of the objects.so C# doesnot allow developer to define a static parameterful property.

0 comments:

 
Counter