Reputation: 6403
I have small question.
When I started to programm my application, I grouped types of same level to class FirstLevel
(all types of that level are derived from FirstLevel
). After that, I started to create generic lists with this type and my code is working with it without any errors.
Now, after some time I need use function Generate
in each class which is derived from FirstLevel
or which's parent is derived from FirstLevel. I thought that interface can be good solution so I started to implement interface IGenerable
to each class which has something in common with FirstLeve
l class (it's derived, or it's parent is derived, or parent of it's parent....) I've implemented it also to FirstLevel class.
And here is beginning of my problem. I need to call generate function on each item which is in List<FirstLevel>
. But I don't know if will be called implementation of IGenerable
in FirstLevel
, or implementations of IGenerable
in derived classes. I hope computer will execute call of implementations in derived classes. Please tell me how it is.
But, if there will be called implementation to FirstLevel
, please help me with it and suggest some solutions. Thanks.
Upvotes: 0
Views: 104
Reputation: 3100
Instead of using Interface you might be better off by adding a virtual function Generate to your base class (FirstLevel) and then override the method in the descendants as needed. Now when you loop through List and call Generate if the object has a overridden method it will execute that one otherwise it will execute the method from the base object.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var objs = new List<FirstLevel> { new FirstLevel(), new SecondLevel(), new ThirdLevel(), new SecondLevel2() };
objs.ForEach(o => o.Generate());
Console.ReadLine();
}
}
public class FirstLevel
{
public virtual void Generate()
{
Console.WriteLine("First Level Generate called.");
}
}
public class SecondLevel : FirstLevel
{
public override void Generate()
{
Console.WriteLine("Second Level generate called.");
}
}
public class SecondLevel2 : FirstLevel
{
}
public class ThirdLevel : SecondLevel
{
public override void Generate()
{
Console.WriteLine("Third Level genrate.");
}
}
}
Upvotes: 2