tags:

views:

1721

answers:

4

Hi,

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.

+8  A: 

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

Colin Mackay
Yeah this was just a stupid mistake on my behalf - thanks for your (and everybody else who contributed) time spent on this though.
Robert W
+7  A: 

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.

Noldorin
A: 

That solution works fine; although to actually use it outside the class the method is in, you need to set the access of SampleMethod to public rather than protected in all of the cases it appears, so:

public class A
{
    public virtual void SampleMethod() 
    {
        Console.WriteLine("lol");
    }
}

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

public class C : B
{
    public override void SampleMethod()
    {
        base.SampleMethod();
    }
}
Callum Rogers
It depends on where SampleMethod is being accessed from. Virtual/Override methods do not have to be public.
Colin Mackay
A: 

The breakpoint is more than likely not being hit because you actually instantiated an instance of the "B" class.

Method override resolution works based on the actual runtime type of the class whose method should be called. So, if you had the following code:

C c = new C();
c.SampleMethod();

and the following:

C c = new C();
B b = (B)c;
b.SampleMethod();

both the runtime types of the class whose SampleMethod will be called is type B.

Mike J