Bas Bas - 1 year ago 61
C# Question

Working with generic IEnumerable<T>

I have written a function which will take a generic IEnumerable and map these objects (If possible) to objects I want to use for an algorithm. I don't have a lot of experience with generic objects or IEnumberables, so I wanted to ask for some advice.

I have written this code:

public static IEnumerable<OtherObject> MyObjectToOtherObject<T>(IEnumerable<T> objects)
if (objects.GetType() == typeof(MyObject))
var data = (IEnumerable<MyObject>)objects;
return data.Select(x => new OtherObject() { // Map the attributes });
return null;

This doesn't work in my code, since it returns null even though the input list is of the type
. I just can't figure out how to cast my
. Is there something I'm doing wrong?

Thanks in advance!

I'm sorry for all the confusion. I have asked this the wrong way. Alex has helped me enough, thank you!

Answer Source

this is wrong.

objects.GetType() == typeof(MyObject)


objects.GetType() == typeof(IEnumerable<T>)

If you need to compare type of nested items:

objects.GetType().GetGenericArguments()[0] == typeof(MyObject)
typeof(T) == typeof(MyObject)

If you are checking if the type can be casted to another type:


or just as

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download