1

Given the scenario...

interface IBase{ 
  void Process(int value);
}

abstract class Base : IBase
{
 public virtual void Process(int value){ throw new NotImplementedException(); }
}

class Implemented: Base, IBase
{
 public void Process(int value)
 {
   // .. some code here.. 
 }
}

I'm trying to write a loop similar to the following.

foreach( Base b in CollectionOfImplemented )
{
 b.Process( // something will go here // );
}

Trying this, it keeps calling Base.Process, instead of Implemented.Process; but the type in the collection is Implemented, not Base. Boxing it seems to work, but I was hoping to see if I could find a more intelligent approach to it, since the Collection will contain other types of objects that also inherit from Base.

2 Answers 2

9

You need to explicitly override Process in Implemented:

class Implemented: Base 
{ 
  public override void Process(int value) 
  { 
    // .. some code here..  
  } 
}

Or you won't get virtual method dispatching.

Also, if your base method is always going to throw that NotImplementedException, it should be marked as abstract instead.

Sign up to request clarification or add additional context in comments.

1 Comment

One of Visual Studio's excellent features is that within the child class, you can start typing the word "override" and Intellisense will show you which virtual methods can be overridden.
0

I think you need to specify "override" for Process in your Implemented class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.