Casting Type array to Generic array?

Posted by George R on Stack Overflow See other posts from Stack Overflow or by George R
Published on 2010-03-28T12:16:40Z Indexed on 2010/03/28 12:23 UTC
Read the original article Hit count: 216

Filed under:
|
|
|

The short version of the question - why can't I do this? I'm restricted to .NET 3.5.


T[] genericArray;

// Obviously T should be float!
genericArray = new T[3]{ 1.0f, 2.0f, 0.0f };

// Can't do this either, why the hell not
genericArray = new float[3]{ 1.0f, 2.0f, 0.0f };

Longer version -

I'm working with the Unity engine here, although that's not important. What is - I'm trying to throw conversion between its fixed Vector2 (2 floats) and Vector3 (3 floats) and my generic Vector<> class. I can't cast types directly to a generic array.


using UnityEngine;

public struct Vector
{
    private readonly T[] _axes;

    #region Constructors
    public Vector(int axisCount)
    {
        this._axes = new T[axisCount];
    }

    public Vector(T x, T y)
    {
        this._axes = new T[2] { x, y };
    }

    public Vector(T x, T y, T z)
    {
        this._axes = new T[3]{x, y, z};
    }

    public Vector(Vector2 vector2)
    {
        // This doesn't work
        this._axes = new T[2] { vector2.x, vector2.y };
    }

    public Vector(Vector3 vector3)
    {
        // Nor does this
        this._axes = new T[3] { vector3.x, vector3.y, vector3.z };
    }
    #endregion

    #region Properties
    public T this[int i]
    {
        get { return _axes[i]; }
        set { _axes[i] = value; }
    }

    public T X
    {
        get { return _axes[0];}
        set { _axes[0] = value; }
    }

    public T Y
    {
        get { return _axes[1]; }
        set { _axes[1] = value; }
    }

    public T Z
    {
        get
        {
            return this._axes.Length (Vector2 vector2)
    {
        Vector vector = new Vector(vector2);

        return vector;
    }

    public static explicit operator Vector(Vector3 vector3)
    {
        Vector vector = new Vector(vector3);

        return vector;
    }
    #endregion
}

© Stack Overflow or respective owner

Related posts about .net-3.5

Related posts about array