tags:

views:

218

answers:

2

I see this Array.ConvertAll method, but it requires a Converter as an argument. I don't see why I need a converter, when I've already defined an implicit one in my class:

    public static implicit operator Vec2(PointF p)
    {
        return new Vec2(p.X, p.Y);
    }

I'm trying to cast an array of PointFs to an array of Vec2s. Is there a nice way to do this? Or should I just suck it up and write (another) converter or loop over the elements?

+6  A: 

Cast doesn't consider user defined implicit conversions so you can't cast the array like that. You can use select instead:

myArray.Select(p => (Vec2)p).ToArray();

Or write a converter:

Array.ConvertAll(points, (p => (Vec2)p));

The latter is probably more efficient as the size of the result is known in advance.

Mark Byers
Mark is correct, I've deleted my answer.
Yuriy Faktorovich
Thanks for copying my answer as your edit...
Noldorin
I already wrote it before I saw your post. The same exact thing happened to me just an hour ago here: http://stackoverflow.com/questions/2067778/sql-for-delete-query/. It happens sometimes. Don't take it personally - it's just a coincidence that two people come with the exact same answer even though it looks like one copied the other.
Mark Byers
@Mark: Apologies... I'm too cynical sometimes. There are users who purposely copy other answers to milk rep, but I'll trust you're not one of them.
Noldorin
I had already hit my rep limit so I didn't get any rep for this question anyway.
Mark Byers
+8  A: 

The proposed LINQ solution using Cast/'Select' is fine, but since you know you are working with an array here, using ConvertAll is rather more efficienct, and just as simple.

var newArray = Array.ConvertAll(array, item => (NewType)item);

Using ConvertAll means a) the array is only iterated over once, not twice, b) the operation is more optimised for arrays (does not use IEnumerator<T>).

Don't let the Converter<TInput, TOutput> type confuse you - it is just a simple delegate, and thus you can pass a lambda expression for it, as shown above.

Noldorin
Works perfectly! Thank you! I thought I had to define the `<types>`.
Mark
No problem. And yeah, in C# 2.0 and before you would have had to define a type - fortunately those days are gone.
Noldorin