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) ?
CodePudding user response:
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();
CodePudding user response:
Definitely not the shortest way, But this approach has its own advantages. and it's only a one-time effort.
Making it configuration-driven will help in modifying the points. if in future you want to add/delete/modify points. It will help you in testing and also provide different02 points.
second, you can manage different points based on the environment as well.
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
public class Root
{
public Point[] Points { get; set; }
}
string json = File.ReadAllText("inut.json");
Root obj = JsonConvert.DeserializeObject<Root>(json); //Use NewtonSoft.json library to deserialize the JSON to object.
Sample JSON:
{
"Points": [{
"X": 0,
"Y": 0
},
{
"X": 10,
"Y": 20
}
]
}