Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast IEnumerable to IEnumerable<T> when T is unknown at compile time

Tags:

c#

generics

I have a sorting extension method with the following signature:

public static IEnumerable<T> CustomSort<T>(this IEnumerable<T> source, string sortProperties)

We wrote it a while back and it has been doing its thing. Now I am creating a custom control and the DataSource property is an IEnumerable (non-generic). Is there any way to get the type of the objects in a non-generic IEnumerable?

I am sure the problem of "sort a custom control data source" has been solved a million times, but I just can't seem to find a solution.

like image 295
Elad Lachmi Avatar asked Dec 02 '12 08:12

Elad Lachmi


1 Answers

There is a fundamental issue here that a type can implement IEnumerable-of-T for multiple T at the same time. But if we exclude that case, a cheeky approach is:

void Evil<T>(IEnumerable<T> data) {...}

IEnumerable source = ...
dynamic cheeky = source;
Evil(cheeky);

This basically offloads this problem to the DLR, letting your Evil-of-T method take it easy.

like image 104
Marc Gravell Avatar answered Oct 09 '22 05:10

Marc Gravell