I'm a bit confused about the following.
Given this class:
public class SomeClassToBeCasted
{
public static implicit operator string(SomeClassToBeCasted rightSide)
{
return rightSide.ToString();
}
}
Why is an InvalidCastException thrown when I try to do the following?
IList<SomeClassToBeCasted> someClassToBeCastedList
= new List<SomeClassToBeCasted> {new SomeClassToBeCasted()};
IEnumerable<string> results = someClassToBeCastedList.Cast<string>();
foreach (var item in results)
{
Console.WriteLine(item.GetType());
}
Because Cast()
doesn't deal with user-specified casts - only reference conversions (i.e. the normal sort of conversion of a reference up or down the inheritance hierarchy) and boxing/unboxing conversions. It's not the same as what a cast will do in source code. Unfortunately this isn't clearly documented :(
EDIT: Just to bring Jason's comment into the post, you can work around this easily with a projection:
IEnumerable<string> results = originalList.Select(x => (string) x);
If only needed for lists, you can do
IEnumerable<string> results =
someClassToBeCastedList.Select(itm => itm.ToString());
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With