jbenckert jbenckert - 1 month ago 18
C# Question

C# .net casting question

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());
}

Answer

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);