Question

In C++, we can do this(pseudo-code):

class A {
    public:
    virtual void a(A a)=0;
    }

class B : A {
    public:
    virtual void a(B b);
}

But when I write the equivalent in C#:

public abstract class A
{
public virtual void a(A a){}
}

public class B : A
{
public override void a(B b){}
}

the compiler gives an error that says B.a doesn't override A.a. Why doesn't C# allow this? It is very resonable to allow this practise because it obeys the principles of polymorphism.

Was it helpful?

Solution

The C++ version of the code doesn't override the method either. But because C++ doesn't have an override keyword¹, you don't get an error for that because the compiler doesn't know you meant to override the method.

If you want the same behavior in C# as you get in C++, you can just remove the override keyword and replace it with new.

¹ It does in C++11, but I'm assuming you didn't use that or else you would have gotten an error.

It is very resonable to allow this practise because it obeys the principles of polymorphism.

No, it doesn't. Consider this:

A a = new B();
a.a(new A());

If B.a overrode A.a, the above code would call B.a with the argument new A(). But B.b takes an argument of type B, so that would not work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top