Saturday, 7 May 2011

Properties and Polymorphism in C#

Properties
In C#, properties are natural extension of data fields. But C# provides a built in mechanism called properties. Usually inside a class, we declare a data field as private and will provide a set of public. In C#, properties are defined using the property declaration syntax. The general form of declaring a property is as follows.
<acces_modifier> <return_type> <property_name>
{
get
{
}
set
{
}
}
SET and GET methods to access the data fields, since the data fields are not directly accessible out side the class. We must use the set/get methods to access the data fields.
Example:

using System;
class Myproperty
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class Myprop
{
public static void Main()
{
Myproperty mc = new Myproperty();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);//Displays 10
}
} 
Properties and Inheritance
The properties of a Base class can be inherited to a Derived class.


using System;
class Base
{
public int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}
Properties & Polymorphism
A Base class property can be polymorphic overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.

using System;
class Base
{
public virtual int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
}
} 
Abstract Properties
It is declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set assessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.

using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
} 

No comments:

Post a Comment