Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling the overridden method from the base class in C#

Tags:

Given the following C# class definitions and code:

 public class BaseClass {     public virtual void MyMethod()     {         ...do something...     } }  public class A : BaseClass {     public override void MyMethod()     {         ...do something different...     } }  public class B : BaseClass {     public override void MyMethod()     {         ...do something different...     } }  public class AnotherObject {     public AnotherObject(BaseClass someObject)     {         someObject.MyMethod(); //This calls the BaseClass method, unfortunately.     } } 

I would like to call the MyMethod() that is actually found in A or B, assuming the object passed in is actually an instance of A or B, not that which is found in BaseClass. Short of doing something like this:

 public class AnotherObject {     public AnotherObject(BaseClass someObject)     {         A temp1 = someObject as A;         if (A != null)         {             A.MyMethod();         }                  B temp2 = someObject as B;         if (B != null)         {             B.MyMethod();         }     } } 

How can I do it?

like image 652
David Avatar asked Feb 19 '10 20:02

David


People also ask

How do you access the overridden method of base class from the derived?

6. How to access the overridden method of base class from the derived class? Explanation: Scope resolution operator :: can be used to access the base class method even if overridden. To access those, first base class name should be written followed by the scope resolution operator and then the method name.

What would you override a method of a base class?

An override method provides a new implementation of the method inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. An override method must have the same signature as the overridden base method.


1 Answers

Which method is called is determined via polymorphism on the type that is passed into the AnotherObject constructor:

AnotherObject a = new AnotherObject(new A()); // invokes A.MyMethod()  AnotherObject b = new AnotherObject(new B()); // invokes B.MyMethod()  AnotherObject c = new AnotherObject(new BaseClass()); //invokes BaseClass.MyMethod()  
like image 52
13 revs, 10 users 51% Avatar answered Nov 08 '22 17:11

13 revs, 10 users 51%