Sample Code
using System;
public interface MyInterface
{
void MyMethod();
}
public class A:MyInterface
{
void MyInterface.MyMethod()
{
Console.WriteLine("Hello World from A");
}
}
public class B:MyInterface
{
void MyInterface.MyMethod()
{
Console.WriteLine("Hello World from B");
}
}
public class C:MyInterface
{
void MyInterface.MyMethod()
{
Console.WriteLine("Hello World from C");
}
}
public class Program
{
public static void Main()
{
C obj = new C();
MyInterface iface=(MyInterface)obj;
iface.MyMethod(); // This will print "Hello World from C"
}
}
The Problem
The Sample code I given above shows the method I used for calling interface method in my project, In the code I have an interface called MyInterface
and it has a method called MyMethod()
, In current sample I called the interface method using object of Class C
, In my project I will have more classes that needs to implement MyInterface and the My method in all these classes need to be called at once.
Take an Example
Currently I have classes A,B,C and all of them have MyMethod()
with Different function body, then later I added another class D and I need to call MyMethod()
in all classes at the same time, the number of classes might be 100's, so is there any way to call all MyMethod()
without creating object for 100's of classes.
CodePudding user response:
A possible solution is to use Polymorphism. You can have a method like this:
public static void ExecuteMyMethods(IEnumerable<MyInterface> instances)
{
foreach(var instance in instances) instance.MyMethod();
}
It will be working for you as needed and you will not have to modify it when new implementation of MyInterface occurs. You will have to pass the new instance from the caller side.
You can also wrap & isolate the logic of getting the collection of MyInterface implementations somewhere, to have it in a single place & once new implementation comes around, you will know where to create an instance of it, for this method to work properly. You can consider using Factory method pattern for that.