Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comment on a method that overrides and is overridden at the same time in C#?

Tags:

c#

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.

like image 825
Xris Avatar asked Dec 03 '11 13:12

Xris


2 Answers

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.

like image 53
Anthony Pegram Avatar answered Oct 24 '22 10:10

Anthony Pegram


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.

like image 2
Alessandro Rossi Avatar answered Oct 24 '22 11:10

Alessandro Rossi