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:
Then you can use:
etc. However, personally I’d just leave it alone, as:
which involves less work (no array allocation / initialization, no operator call).