Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of .Cast over .Select?

Tags:

c#

linq

I have a type with implicit conversion operators to most base types and tried to use .Cast<string>() on a collection of this type, which failed. As I dug into it, I noticed that casting via as doesn't use implicit or explicit conversion and just won't compile, so I guess that's where .Cast falls down. So this fails

var enumerable = source.Cast<string>();

but this works

var enumerable = source.Select(x => (string)x);

So what's the benefit of Cast? Sure, it's a couple of characters shorter, but seems a lot more limited. If it can be used for conversion, is there some benefit other than the more compact syntax?

like image 421
Arne Claassen Avatar asked Aug 20 '11 14:08

Arne Claassen


2 Answers

Cast usage

The benefit of Cast comes when your collection only implements IEnumerable (ie. not the generic version). In this case, Cast converts all elements to TResult by casting, and returns IEnumerable<TResult>. This is handy, because all the other LINQ extension methods (including Select) is only declared for IEnumerable<T>. In code, it looks like this:

IEnumerable source = // getting IEnumerable from somewhere

// Compile error, because Select is not defined for IEnumerable.
var results = source.Select(x => ((string)x).ToLower());

// This works, because Cast returns IEnumerable<string>
var results = source.Cast<string>().Select(x => x.ToLower());

Cast and OfType are the only two LINQ extension methods that are defined for IEnumerable. OfType works like Cast, but skips elements that are not of type TResult instead of throwing an exception.

Cast and implicit conversions

The reason why your implicit conversion operator is not working when you use Cast is simple: Cast casts object to TResult - and your conversion is not defined for object, only for your specific type. The implementation for Cast is something like this:

foreach (object obj in source)
    yield return (TResult) obj;

This "failure" of cast to do the conversion corresponds to the basic conversion rules - as seen by this example:

YourType x = new YourType(); // assume YourType defines an implicit conversion to string
object   o = x;

string bar = (string)x;      // Works, the implicit operator is hit.
string foo = (string)o;      // Fails, no implicit conversion between object and string
like image 86
driis Avatar answered Nov 14 '22 00:11

driis


I checked the MSDN page for Cast<TResult>, and it is an extension method to types that implement (the non-generic) IEnumerable interface.

It can convert a collection class (such as ArrayList) which doesn't implement IEnumerable<T> to one that does, allowing the richer operations (such as Select<T>) to be performed against it.

like image 6
Eric Olsson Avatar answered Nov 13 '22 23:11

Eric Olsson