I have a list which is declared below, at the start I default the list items to { -1, - }. please note that throughout the program the list size is fixed at 2.
List<int> list = new List<int>(new int[] {-1, -1});
My question is regarding, what would be the best approach if I need to overwrite the two values in the list.
int x = GetXValue();
int y = GetYValue();
Approach 1:
list = new List<int>(new int[] {x, y});
Approach 2:
list[0] = x;
list[1] = y;
What would be a better approach? With the second approach, even though I am sure there are 2 values set initially, I can run a risk of the Argument index out of range
exception. But the first approach might eat more memory (correct me if I am wrong!) since I am creating a new list every time.
Is there a simpler, and/or better solution
Or is there a simpler and better solution?
Yes. Since the list has a fixed size, use a real object such as System.Drawing.Point:
Point p = new Point(1, -1);
p = new Point(5, 10);
Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);
why not a custom class, something like, especially since it is a fixed size.
class MyClass {
public MyClass(int x, int y) {
}
public int X { get; set; }
public int Y { get; set; }
public int[] ToArray() {
return new[] { X, Y };
}
public List<int> ToList() {
return ToArray().ToList();
}
}
Struct could work too
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y):this()
{
this.X = x;
this.Y = y;
}
}
Point p = new Point(-1, -1);
// ...
p.X = newX;
p.Y = newY;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With