Search code examples
c#arrayscastinginitializationpoint

The shortest way to initialize a point array?


I am looking for the shortest way in terms of writing to declare an array of points. My problem is that I have humongous point data that I want to hardcode as an initialization.

These initializations repeat the 'new Point' multiple times:

Point[] points1 = new[] { new Point { X = 0, Y = 0 }, new Point { X = 20, Y = 120 }, new Point { X = 40, Y = 60 }, }; // kinda long typing

Point[] points2 = { new Point(0, 0), new Point(20, 120), new Point(40, 60) }; // better

Alternatively I could declare the array like so:

int[,] arr = new int[,] { { 0, 0 }, { 20, 120 }, { 40, 60 } }; // so far shortest typing

But how can I cast int[,] to Point[] ? Are there other alternatives (like using lists) ?


Solution

  • You can change new[] to new Point[]. This way, you can use target-typed new in the array elements:

    Point[] points1 = new Point[] { 
        new() { X = 0, Y = 0 }, 
        new() { X = 20, Y = 120 },
        new() { X = 40, Y = 60 }, 
    };
    

    If Point has a 2-parameter constructor, this can be even shorter:

    Point[] points1 = new Point[] { 
        new(0, 0),
        new(20, 120),
        new(40, 160)
    };
    

    If points1 is a local variable, you can make it even shorter by making the variable implicitly typed:

    var points1 = new Point[] { 
        new(0, 0),
        new(20, 120),
        new(40, 160)
    };
    

    If you want to make this really short in the long run, you can make a (int, int)[], then convert to Point[]:

    Point[] points1 = new[] { 
        (0, 0),
        (20, 120),
        (40, 160)
    }.Select(x => new Point(x.Item1, x.Item2)).ToArray();
    

    In C# 12+, you can also use a collection expression:

    Point[] points1 = [ 
        new(0, 0),
        new(20, 120),
        new(40, 160)
    ];