I need to initialize an array of three points. I want to write it like below, but only once for three elements.
Point P = new Point { X = 0, Y = 1 };
Point[] P = new Point[3];// <---- ?
How to write correctly?
I need to initialize an array of three points. I want to write it like below, but only once for three elements.
Point P = new Point { X = 0, Y = 1 };
Point[] P = new Point[3];// <---- ?
How to write correctly?
Here is the code for creating the array of 3 different points:
Point[] points = new Point[] { new Point { X = 0, Y = 1 }, new Point { X = 2, Y = 1 }, new Point { X = 0, Y = 3 } };
There’s not really a shorthand for that. For three, just write it three times:
Point initial = new Point { X = 0, Y = 1 };
Point[] P = new Point[3] { initial, initial, initial };
Example below you can create 10 Point
using Enumerable.Range
var points = Enumerable.Range(0, 10)
.Select(x => new Point {X = 0, Y = 1})
.ToArray();
Because you question deals about a static fixed length array of point with static coordinates, no needs to bother with LINQ and loops in this context when array initialization is that simple.
So you can initialize an array this way:
Point[] P = new Point[]
{
new Point { X = 0, Y = 1 },
new Point { X = 0, Y = 1 },
new Point { X = 0, Y = 1 },
...
};
or use duck typing type inference (thanks minitech):
var P = new []
{
new Point { X = 0, Y = 1 },
new Point { X = 0, Y = 1 },
new Point { X = 0, Y = 1 },
...
};
Here is the shortest solution:
Point[] points = Enumerable.Repeat<Point>(new Point(0, 1), 3).ToArray();