C # Polymorphism and inheritance method

Consider the following classes:

public class X {};
public class Y : X {};
public class Z : X {};

public class A {
    public bool foo (X bar) { 
        return false;
    }
};

public class B : A { 
    public bool foo (Y bar) { 
       return true;
    }
};    

public class C : A { 
    public bool foo (Z bar) { 
       return true;
    }
};

Is there a way to achieve the next desired exit?

A obj1 = new B();
A obj2 = new C();

obj1.foo(new Y()); // This should run class B implementation and return true
obj1.foo(new Z()); // This should default to class A implementation and return false

obj2.foo(new Y()); // This should default to class A implementation and return false
obj2.foo(new Z()); // This should run class C implementation and return true

The problem I am facing is that an implementation of class A is always called regardless of the arguments passed.

+4
source share
2 answers

I believe that you want to define a virtual method and override it with a signature containing derived types. This is not possible, since the method that redefines the base must have the same signature. This is probably due to the fact that the compiler must apply complex bypass rules. So, as suggested in the previous answer, to get the desired behavior:

public class A { public virtual bool Foo (X bar) { ... } }
public class B { 
    public override bool Foo (X bar) {
         if(bar is Y) { ... } 
         else base.Foo(bar);
    }
}
+3
source

foo A virtual, .

public class A { public virtual bool Foo (X bar) { ... } }
public class B { public override bool Foo (X bar) { ... } }

, , B C, , . A (A obj1 = new B();), , A.

+5

All Articles