Here is the scenario
public class Connection
{
public virtual void close()
{
/*Some code */
}
}
public interface IHttpRelay
{
void close();
}
public class HttpConnection: Connection,IHttpRelay
{
public /*keyword*/ void close()
{
base.close();
}
}
public class Http:HttpConnection
{
public override void close()
{
/*Some code */
}
}
My question is to know if i should declare the method close() in HttpConnection class with an override or virtual keyword since it overrides and is overridden at the same time.
You need to mark it with override
. If you mark it with virtual
in HttpConnection
, it will hide the base class implementation, not override it. As a result, it could not be used polymorphically. Mark one method virtual, the rest should simply be overrides.
As a simple example
class A
{
public virtual void Frob()
{
Console.WriteLine("A");
}
}
class B : A
{
public virtual void Frob()
{
Console.WriteLine("B");
}
}
class C : B
{
public override void Frob()
{
Console.WriteLine("C");
}
}
Here, B redefines a virtual Frob, it does not override. It follows your example. However, when working with an instance of C through the reference of A, something "unexpected" happens.
A obj = new C();
obj.Frob(); // "A" is written to the screen, not "C"
What is written to the screen is "A", you did not get the polymorphic behavior you would expect. When you hide a member instead of override it, you only get the new behavior via the reference of the hiding class. When referenced through a base class, you receive the base behaviors! This is typically not what you desire in a virtual/override polymorphic scenario. If you replace the virtual
with override
in class B and then run the above snippet, the output is what you would expect.
The override modifier doesn't prevent the derived classes to override the same method once more. To prevent this your should also use the sealed modifier with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With