Bas Bas - 19 days ago 8
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 });
}
else
return null;
}


This doesn't work in my code, since it returns null even though the input list is of the type
MyObject
. I just can't figure out how to cast my
IEnumerable<T>
to
IEnumerable<MyObject>
. 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

this is wrong.

objects.GetType() == typeof(MyObject)

Correct:

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:

objects.GetType().GetGenericArguments()[0].IsAssignableFrom(typeof(MyObject))

or just as

typeof(T).IsAssignableFrom(typeof(MyObject))
Comments