Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET List best approach

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

like image 686
topgun_ivard Avatar asked Aug 13 '10 22:08

topgun_ivard


3 Answers

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);
like image 58
Juliet Avatar answered Oct 19 '22 18:10

Juliet


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();
    }
}
like image 1
Jarrett Meyer Avatar answered Oct 19 '22 18:10

Jarrett Meyer


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;
like image 1
Mike Koder Avatar answered Oct 19 '22 19:10

Mike Koder