Using C# 10 I have the interface:
public Interface IEndpoint {
void Map();
}
I need to find classes that implement IEndpoint
in Assembly of Program
class.
Then, for each class, I need to call the method Map
:
IEnumerable<IEndpoint> endpoints =
typeof(Program).Assembly
.GetTypes()
.Where(x => x.GetInterface(nameof(IEndpoint)) == typeof(IEndpoint));
I am getting the error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Type>' to 'System.Collections.Generic.IEnumerable<IEndpoint>'
How can I solve this and call the method Map
for each found class?
Update
I think I got it:
IEnumerable<Type> types = typeof(Program).Assembly.GetTypes().Where(x => x.IsAssignableFrom(typeof(IEndpoint)) && !x.IsInterface);
foreach (Type type in types) {
IEndpoint? endpoint = (IEndpoint?)Activator.CreateInstance(type);
endpoint?.Map();
}
Am I missing something in my implementation?
I am asking because I've seen many approaches to this problem.
Not sure if mine is the most recent approach.