user236520
user236520

Reputation:

C#: Storing a reference to an array location in an object

I have a c# object that sets the values of 2 floating point numbers. I have many such objects. I would like to store these floating point numbers in an array. So the layout would be something like this:

Given a float array: float[] vec = new float[6]

Object 1 sets the values of vec[0] and vec[1]
Object 2 sets the values of vec[2] and vec[3]
Object 3 sets the values of vec[4] and vec[5]

How can I store references on the objects so they will access the correct vector element? I could store an index, but in the old-fashioned c++ world I could store a pointer directly into array.

Upvotes: 2

Views: 4457

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 660138

When I need to use a C-style pointer to the middle of an array, I just make a generic struct that contains a reference to the array and the current index, and use that. Feel free to steal my code:

http://blogs.msdn.com/b/ericlippert/archive/2011/03/10/references-and-pointers-part-two.aspx

Upvotes: 5

Dan Bryant
Dan Bryant

Reputation: 27505

C# is specifically designed so that you cannot store references to array elements or other 'non-root' memory locations in safe, managed code. Having such references would significantly complicate garbage collection and this capability in C is a known potential culprit for introducing nasty bugs. For instance, you can allocate an array on the stack in C and pass a reference to an array element. If that reference is kept around after the stack is unwound, it now points to an arbitrary location and writing to the reference could result in data corruption.

Upvotes: 1

Aliostad
Aliostad

Reputation: 81660

You may use a structure like PointF:

PointF[] points = new PointF[3];
Console.WriteLine("X:{0}, Y:{0}", points[0].X, points[0].Y);

Or you can create your own structure:

public struct Vector
{
    public int X;
    public int Y;
}

Upvotes: 0

Related Questions