tags:

views:

183

answers:

1

In answering this question http://stackoverflow.com/questions/808725/why-does-a-linq-castt-operation-fail-when-i-have-an-implicit-cast-defined

I have found that there are a number of ways to implicitly cast between objects.

Consider the following two classes:

public class Class1 
{ 
    public int Test1;
}
public class Class2
{
    public int Test2;
    public static implicit operator Class1(Class2 item)
    {
        return new Class1 { Test1 = item.Test2 };
    }
}

In order to convert a List to List we can do any of the following:

List<Class2> items = new List<Class2> { new Class2 { Test2 = 9 } };

foreach (Class1 item in items)
{
    Console.WriteLine(item.Test1);
}

foreach (Class1 item in items.ConvertAll<Class1>(i=>i))
{
    Console.WriteLine(item.Test1);
}

foreach (Class1 item in items.Select<Class2, Class1>(i=> i))
{
    Console.WriteLine(item.Test1);
}

foreach (Class1 item in items.Select(i=>i))
{
    Console.WriteLine(item.Test1);
}

But which is clearer to read and understand what is going on?

+2  A: 

The first, naturally. The whole point of an implicit cast is that the two types are sufficiently similar that it makes conceptual sense to just figure that they are the same.

Would you balk at this?

List<byte> items = new List<byte> { 1, 2, 3, 4 };

foreach (int i in items) // since bytes implictly cast to ints
{
    Console.WriteLine(i + 1000);
}

If that's OK with you, but you don't like your first formulation in the question above, then I think you should use an explicit cast instead.

mquander
Yes I would. But if rather than a foreach loop I needed to pass a List<Class1> and all I had was a List<Class2> I would need sometype of conversion to happen. The above snippets all provide this function, but which is easier.
David McEwing