Suppose you have types like the following:
interface IThing { }
class Thing : IThing { }
LINQ allows you to create a projection that changes the compile-time generic type of an IEnumerable<>
via the Enumerable.Cast<>()
and Enumerable.OfType<>()
extension methods.
IEnumerable<IThing> things = new IThing[] {new Thing()};
IEnumerable<Thing> things2 = things.Cast<Thing>();
IEnumerable<Thing> things3 = things.OfType<Thing>();
When things2
is evaluated, the Cast<>()
method will try to cast all of the values in things
into Thing
s. If it encounters a value that cannot be cast, an InvalidCastException
will be thrown.
When things3
is evaluated, the OfType<>()
method will do the same, except that if it encounters a value that cannot be cast, it will simply omit that value rather than throw an exception.
Due to the generic type of these methods, they cannot invoke Conversion Operators or perform numeric conversions.
double[] doubles = new[]{1,2,3}.Cast<double>().ToArray(); // Throws InvalidCastException
You can simply perform a cast inside a .Select()
as a workaround:
double[] doubles = new[]{1,2,3}.Select(i => (double)i).ToArray();