0

I have three classes. First of them is abstract, and it is inherited by child class, which is again inherited. How to call method from the third class in abstract one?

Example code:

public abstract class DoSth { public void DoSomething() { Console.WriteLine("I'm doing something"); this.DoSomethingBigger(); } protected abstract void DoSomethingBigger(); } public class Writer : DoSth { protected override void DoSomethingBigger() { Console.WriteLine("I'm writting"); } } public class BookWriter : Writer { protected new void DoSomethingBigger() { Console.WriteLine("I'm writting a book"); } } 

How to call DoSomethingBigger() from a BookWriter class? When I make an instance of a BookWriter and I call DoSomething() my output is

I'm doing something I'm writting 

but I want

I'm doing something I'm writting a book 
2
  • 2
    You are not overriding the method in the 3rd class, you are basically creating an entirely new method that the base knows nothing about. Did you mean to override it instead? Commented Jul 28, 2018 at 15:18
  • Possible duplicate of Confused about "override" vs. "new" in C# Commented Jul 28, 2018 at 16:59

2 Answers 2

2

You are not overriding the method in the 3rd class, you are basically creating an entirely new method that the base knows nothing about. see here for more info. It's no different than changing the name of the method in BookWriter to something completely different like DoSomethingElseAltogether(), now it's much more obvious that you cannot call it from the base class.

Instead, you should override in the third class:

public class BookWriter : Writer { protected override void DoSomethingBigger() { Console.WriteLine("I'm writting a book"); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

might I add that you probably want to base.DoSomething() to ensure it does what's in the superclass too
@Persistence Well maybe, depends on your use case. OP doesn't have it in the middle class, and if they did, I don't think it's what is required here.
2

By marking your DoSomethingBigger method with new keyword you hide the initial DoSomethingBigger method instead of overriding it.

You should rewrite your code this way for it to work

public abstract class DoSth { public void DoSomething() { Console.WriteLine("I'm doing something"); this.DoSomethingBigger(); } protected abstract void DoSomethingBigger(); } public class Writer : DoSth { protected override void DoSomethingBigger() { Console.WriteLine("I'm writting"); } } public class BookWriter : Writer { protected override void DoSomethingBigger() { Console.WriteLine("I'm writting a book"); } } 

2 Comments

@Pavel You cannot have virtual and override in the same method signature. This code doesn't compile.
Nice to hear that :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.