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!
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With