Luke Pothier Luke Pothier - 1 month ago 5
C# Question

.NET Portable - Calling .Select() on a string

I am trying to call the

.Select()
Linq extension method on a string from within a PCL, but I'm unable to compile the project. Calling
.Select()
on a string from a separate, non-portable project is compilable. I can see that
.Select()
takes in
this IEnumerable<TSource> source
. The string (and String) types implement
IEnumerable
inside of the .NETPortable assembly, so why should
.Select()
be unavailable? Can the compiler not implicitly convert strings to character arrays with PCLs for some reason?

Answer

The compiler needs to implicitly convert a string to an IEnumerable<char>.

Whether this works depends on the platform(s) you are targeting with the portable library and thus what subset of the .NET Framework is available. If you target .NET Framework 4 and for instance Xamarin, you have a different subset than if you were targeting .NET Framework 4.5.1 and Xamarin. In the former case, the compiler will reject an implicit cast from string to IEnumerable<char>, while in the latter case it is accepted.

So the simple solution (if it is viable for you) would be to target .NET Framework 4.5.1 and higher. Otherwise, you may cast your string to a sequence of characters, e.g., using .Cast<char>().

Comments