Reputation: 86600
I have some classes implementing an interface:
class FirstImplementer : IInterface { ... }
class AnotherImplementer : IInterface { ... }
Somewhere in the code, I got a list of instances of IInterface.
List<IInterface> MyList;
I want to know for each IInterface instance what is the implementer class of that specific instance (FirstImplementer or AnotherImplementer).
Upvotes: 0
Views: 1057
Reputation: 56536
foreach (var item in MyList)
{
var theType = item.GetType();
// why did you want theType, again?
// you generally shouldn't be concerned with how your interface is implemented
}
This alternative may be more useful, depending on what you're trying to do:
foreach (var item in MyList)
{
if (item is FirstImplementer)
{
var firstImpl = (FirstImplementer)item;
// do something with firstImpl
}
else if (item is AnotherImplementer)
{
var anotherImpl = (AnotherImplementer)item;
// do something with anotherImpl
}
}
It's generally better to use is
or as
over reflection (e.g. GetType
) when it might make sense to do so.
Upvotes: 1
Reputation: 3262
If you need to get the first type argument if any, and null if no such type argument even exists for each instance in your list, which at design time you syntactically observe as interface references then you could use the GetGenericArguments method of the Type type.
Here's a little helper method which takes a bunch of objects which may be null, but which would surely implement your interface if they weren't (they would have a runtime type that did) and yields a bunch of types which represent (in respective order) the discovered type arguments in a SomeImplementer pattern:
public IEnumerable<Type> GetTypeArgumentsFrom(IEnumerable<IInterface> objects) {
foreach (var obj in objects) {
if (null == obj) {
yield return null; // just a convention
// you return null if the object was null
continue;
}
var type = obj.GetType();
if (!type.IsGenericType) {
yield return null;
continue;
}
yield return type.GetGenericArguments()[0];
}
}
Upvotes: 0
Reputation: 172646
foreach (var instance in MyList)
{
Type implementation = instance.GetType ();
}
Upvotes: 0
Reputation: 6220
You can just use .GetType()
on the instances in MyList
and go from there.
MyList[0].GetType()
> This is the same as typeof(FirstImplementer)
et al.
Upvotes: 2