Wednesday, March 01, 2006

Method Hiding and Use of Virtual Keyword in C#.NET

1) Method Hiding

class Base
{
public Base() { Console.Write("Base constructor \n");}
public void show() {Console.Write("Base Show \n");}
}
class Child : Base
{
public Child() { Console.Write("Child constructor \n");}
public void show() {Console.Write("Child Show \n");}
// It will give you the compilation Warning
// Put NEW keyword for Intentionally "Method Hiding" No Warning will come
// public new void show() {Console.Write("Child Show \n");}
}
class Class1
{
static void Main(string[] args)
{
Base b1 = new Base();
b1.show(); // 1) Base constructor 2) Base Show
Child c1 = new Child();
c1.show(); // 1) Base constructor 2) Child constructor 3) Child Show
Base b11 = new Child();
b11.show(); // 1) Base constructor 2) Child constructor 3) Base Show
//Child c11 = new Base();
// give compilation Error Can't explict conversion
//Child c11 = (Child) new Base();
// if you do explicit type conversion then run time error say "Invalid Conversion"
//c11.show();
Console.ReadLine();
}
}
1) Virtual Keyword
class Base
{
public Base() { Console.Write("Base constructor \n");}
public virtual void show() {Console.Write("Base Show \n");}
}
class Child : Base
{
public Child() { Console.Write("Child constructor \n");}
public override void show() {Console.Write("Child Show \n");}
}
class Class1
{
static void Main(string[] args)
{
Base b1 = new Base();
b1.show(); // 1) Base constructor 2) Base Show
Child c1 = new Child();
c1.show(); // 1) Base constructor 2) Child constructor 3) Child Show
Base b11 = new Child();
b11.show(); // 1) Base constructor 2) Child constructor 3) Child Show
//Child c11 = new Base();
// give compilation Error Can't explict conversion
//Child c11 = (Child) new Base();
// if you do explicit type conversion then run time error say "Invalid Conversion"
//c11.show();
Console.ReadLine();
}
}


Ritesh Kumar Kesharwani

A D I T I , B A N G A L O R E
Software Professional





Relax. Yahoo! Mail virus scanning helps detect nasty viruses!