Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit cast using Linq

Say I have a list with integers (var identifiers = Enumerable.Empty<int>()).

With this list I can cast the individual items to another type:

var castedIdentifiersLong = identifiers.Cast<long>();
var castedIdentifiersString = identifiers.Cast<string>();

We can use Select<TSource, TTarget>() to use implicit casting:

var mappedIdentifiersLong = identifiers.Select<int, long>(x => x);
var mappedIdentifiersString = identifiers.Select<int, string>(x => x);

Obviously the last statement fails, because int cannot be implicitly casted to string. This is intentionally.

Is there a way that I can define an extension method (say CastImplicitly<T>), where I can only define one of the two generic types and it would figure out the first type from the source enumerable?

var unwanted = identifiers.ImplicitCast<string>();
var wanted = identifiers.ImplicitCast<long>();

In this case unwanted shouldn't even compile, because int isn't implicitly castable to string. But on the other hand, wanted should compile, because it is implicitly castable to long.

like image 987
Caramiriel Avatar asked Aug 31 '25 18:08

Caramiriel


1 Answers

Is there a way that I can define an extension method (say CastImplicitly<T>), where I can only define one of the two generic types and it would figure out the first type from the source enumerable?

Not if the input is generic. The compiler cannot partially infer generic parameters - you either have to specify all generic parameters or none and let the compiler infer.

Even if you could, the compiler still would not allow an implicit cast between generic types.

If you want the compiler to identify invalid casts at compile-time you could do an explicit cast:

var mappedIdentifiersString = identifiers.Select(x => (string)x);  // fails at compile time if x is an int.

It may not catch every possible invalid cast at compile-time (e.g. casts to/from object are always allowed at compile-time) but it does fail for your specific int to string scenario.

like image 60
D Stanley Avatar answered Sep 02 '25 08:09

D Stanley