dineth
asked on
virtual & override keywords
Hi experts !!
Wanna know the point of using virtual keyword for a methods declaration & override keyword in a subclasses implementation for a certain inherited method.
class A
{
public virtual void methodA()
{
Console.WriteLine("base methodA()");
}
}
class B : A
{
//override inherited methodA()
public override void methodA()
{
base.methodA();
Console.WriteLine("sub methodA()");
}
}
Now tell me itsn't this the same as the above code snippet ?? The only thing I've not done explicit declaration as virtual in base implementation & override in the subclasses implementation.
class A
{
public void methodA()
{
Console.WriteLine("base methodA()");
}
}
class B : A
{
public void methodA()
{
base.methodA();
Console.WriteLine("sub methodA()");
}
}
What's the point of virtual method declaration ??
ThankX
--Din--
Wanna know the point of using virtual keyword for a methods declaration & override keyword in a subclasses implementation for a certain inherited method.
class A
{
public virtual void methodA()
{
Console.WriteLine("base methodA()");
}
}
class B : A
{
//override inherited methodA()
public override void methodA()
{
base.methodA();
Console.WriteLine("sub methodA()");
}
}
Now tell me itsn't this the same as the above code snippet ?? The only thing I've not done explicit declaration as virtual in base implementation & override in the subclasses implementation.
class A
{
public void methodA()
{
Console.WriteLine("base methodA()");
}
}
class B : A
{
public void methodA()
{
base.methodA();
Console.WriteLine("sub methodA()");
}
}
What's the point of virtual method declaration ??
ThankX
--Din--
Since A is the base class of B, you can have an A reference carry a B object:
private A refA;
refA=new B();
refA.MethodA(); // will write sub on virtual method, but base on non-virtual method
The compiler does check at runtime to call the right method, but with non-virtual methods the compiler just assumnes which to call depending on the reference at compile-time. That's the difference.
private A refA;
refA=new B();
refA.MethodA(); // will write sub on virtual method, but base on non-virtual method
The compiler does check at runtime to call the right method, but with non-virtual methods the compiler just assumnes which to call depending on the reference at compile-time. That's the difference.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks guys !! thanks for all the help...
--Din--
--Din--
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_10_5_3.asp
Regards.