Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override an overridden method (C#)

Tags:

c#

inheritance

I'm trying to override an overridden method (if that makes sense!) in C#.

I have a scenario similar to the below, but when I have a breakpoint in the SampleMethod() in the "C" class it's not being hit, whilst the same breakpoint in the "B" method is being hit.

public class A {       protected virtual void SampleMethod() {} }  public class B : A  {       protected override void SampleMethod()       {            base.SampleMethod();        } }  public class C : B {       protected override void SampleMethod()        {            base.SampleMethod();        } } 

Thanks in advance!


Edit:

Ok, the context would help:

This is in the context of a composite control so class A inherits from CompositeControl and calls SampleMethod() after overriding the CreateChildControls() method.

like image 581
Robert W Avatar asked Jul 20 '09 11:07

Robert W


People also ask

Can you override an overridden method C ++?

Access Overridden Function in C++To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.

How do you override a derived class method?

An override method is a new implementation of a member that is inherited from a base class. The overridden base method must be virtual, abstract, or override. Here the base class is inherited in the derived class and the method gfg() which has the same signature in both the classes, is overridden.

How do you prevent a method from being overridden in C#?

To prevent being overridden, use the sealed in C#. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.

Can you override inherited methods?

A derived class has the ability to redefine, or override, an inherited method, replacing the inherited method by one that is specifically designed for the derived class. The derived class may want to inherit many of the base class's methods because these methods are suited to the behavior of the derived class.


2 Answers

Overriding can be performed in a chain as long as you like. The code you have shown is correct.

The only possible explanation for the behaviour you are seeing is that the object to which you are referring is actually of type B. I suggest that you double check this, and if things still don't make sense, post the other appropiate code.

like image 164
Noldorin Avatar answered Oct 22 '22 09:10

Noldorin


Without seeing the code that calls SampleMethod, my guess would be that you have an object of type B and call SampleMethod on that.

like image 44
Colin Mackay Avatar answered Oct 22 '22 10:10

Colin Mackay