Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use an array-initializer syntax for a custom vector class?

I have a class roughly designed as such:

class Vector3
{
    float X;
    float Y;
    float Z;

    public Vector3(float x, float y, float z)
    {
        this.X = x;
        this.Y = y;
        this.Z = z;
    }
}

I have other classes implementing it as properties, for example:

class Entity
{
    Vector3 Position { get; set; }
}

Now to set an entity's position, I use the following:

myEntity.Position = new Vector3(6, 0, 9);

I would like to shorten this up for the user by implementing an array-like initializer for Vector3:

myEntity.Position = { 6, 0, 9 };

However, no class can inherit arrays. Moreover, I know I could somehow manage to get this with minor hacks:

myEntity.Position = new[] { 6, 0, 9 };

But this is not the point here. :)

Thanks!

like image 506
Lazlo Avatar asked Sep 15 '25 10:09

Lazlo


2 Answers

There is no defined syntax to use array initializer syntax, except for in arrays. As you hint, though, you can add an operator (or two) to your type:

    public static implicit operator Vector3(int[] value)
    {
        if (value == null) return null;
        if (value.Length == 3) return new Vector3(value[0], value[1], value[2]);
        throw new System.ArgumentException("value");
    }
    public static implicit operator Vector3(float[] value)
    {
        if (value == null) return null;
        if (value.Length == 3) return new Vector3(value[0], value[1], value[2]);
        throw new System.ArgumentException("value");
    }

Then you can use:

obj.Position = new[] {1,2,3};

etc. However, personally I'd just leave it alone, as:

obj.Position = new Vector3(1,2,3);

which involves less work (no array allocation / initialization, no operator call).

like image 75
Marc Gravell Avatar answered Sep 18 '25 10:09

Marc Gravell


The entire point of the request is to reduce the overall amount of code. It is simply more convenient to do { 1, 2, 3 }. It seems odd that C# does not allow you to overload operators to do this, or allow another way to utilize array initializers for custom reference types.

like image 41
Tyler Harden Avatar answered Sep 18 '25 09:09

Tyler Harden