Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .net casting question

Tags:

c#

.net

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());
}
like image 647
jbenckert Avatar asked Jan 14 '10 16:01

jbenckert


2 Answers

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);
like image 131
Jon Skeet Avatar answered Sep 25 '22 12:09

Jon Skeet


If only needed for lists, you can do

IEnumerable<string> results =
        someClassToBeCastedList.Select(itm => itm.ToString());

instead.

like image 40
herzmeister Avatar answered Sep 24 '22 12:09

herzmeister