jbenckert
jbenckert

Reputation: 964

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

Upvotes: 7

Views: 312

Answers (3)

Pramodkumar
Pramodkumar

Reputation: 21

You can use this i to got similar problem it will helps you

IEnumerable results = originalList.Select(x => (string) x);

Upvotes: -1

Jon Skeet
Jon Skeet

Reputation: 1500525

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

Upvotes: 16

herzmeister
herzmeister

Reputation: 11287

If only needed for lists, you can do

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

instead.

Upvotes: 6

Related Questions