Linq method throw an InvalidCastException

Hello,

I’m trying to convert an array of Vector3 into an array of MyCustomVector.

MyCustomVector have an implicit cast so you can convert Vector3 into MyCustomVector.

But why does the line 27 throws an InvalidCastException ?

using UnityEngine;
using System.Linq;

public struct MyCustomVector
{
    public float x, y, z;

    public MyCustomVector(Vector3 vector3)
    {
        x = vector3.x;
        y = vector3.y;
        z = vector3.z;
    }

    public static implicit operator MyCustomVector (Vector3 vector3)
    {
        return new MyCustomVector(vector3);
    }
}


public class Test : MonoBehaviour
{
    private void Start()
    {
        Vector3[] vectors = new Vector3[4];
        MyCustomVector[] customVectors = vectors.Cast<MyCustomVector>().ToArray<MyCustomVector>(); //InvalidCastException
    }
}

Here is the error message :

Thank you in advance!

Well, the issue here is that even though a type conversion operator is used like a cast, it actually is not a cast. You can not directly reinterpret (that’s what casting is) a Vector3 as your custom type. You can only convert it. You can use the Select extension method to do your conversion:

MyCustomVector[] customVectors = vectors.Select(v=>(MyCustomVector)v).ToArray(); 

This is essentially a shorter (but slightly slower with more overhead) approach to do this

MyCustomVector[] customVectors = new MyCustomVector[vectors.Length];
for(int i = 0; i < vectors.Length; i++)
    customVectors _= vectors*;*_