Cast

Download .net eBook

Example

Cast is different from the other methods of Enumerable in that it is an extension method for IEnumerable, not for IEnumerable<T>. Thus it can be used to convert instances of the former into instances of the later.

This does not compile since ArrayList does not implement IEnumerable<T>:

var numbers = new ArrayList() {1,2,3,4,5};
Console.WriteLine(numbers.First());

This works as expected:

var numbers = new ArrayList() {1,2,3,4,5};
Console.WriteLine(numbers.Cast<int>().First()); //1

Cast does not perform conversion casts. The following compiles but throws InvalidCastException at runtime:

var numbers = new int[] {1,2,3,4,5};
decimal[] numbersAsDecimal = numbers.Cast<decimal>().ToArray();

The proper way to perform a converting cast to a collection is as follows:

var numbers= new int[] {1,2,3,4,5};
decimal[] numbersAsDecimal = numbers.Select(n => (decimal)n).ToArray();

Stats

Contributors: 2
2016-09-28
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook