random .NET and web development musings

If you want to cast an Enumerable’s inner type, you can use LINQ:

var casted = myEnumerable.Cast<int>();

But what when you only know the inner type (int) at runtime?

The easiest way is the following reflection magic:

public static IEnumerable Cast(this IEnumerable self, Type innerType)
	var methodInfo = typeof (Enumerable).GetMethod("Cast");
	var genericMethod = methodInfo.MakeGenericMethod(innerType);
	return genericMethod.Invoke(null, new [] {self}) as IEnumerable;
Post a comment