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 withvirtualinHttpConnection, 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
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.
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
virtualwithoverridein class B and then run the above snippet, the output is what you would expect.