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?
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 };
System.Drawing.Point, which is a value type. I’ll delete this if that’s not the case.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();
Enumerable.Repeat()Point is a value type, so that's not possible, unless the OP created his own custom Point class.Here is the shortest solution:
Point[] points = Enumerable.Repeat<Point>(new Point(0, 1), 3).ToArray();
var instead of specifying the type, omit the generic arguments to Repeat, and remove the unneeded whitespace.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 },
...
};