Patrick Lorio Patrick Lorio - 3 months ago 8
C# Question

Reference a value type element in an array

I have a value type

Node
and an array
grid


private Node[,] grid;

public struct Node {
public byte occupant;
public Direction toTarget;
public float distance;
}

public enum Direction {
UP, LEFT, RIGHT, DOWN
}


How do I reference an element instead of copying it on assignment?

Example

Node node = grid[0,0];
node.occupant = 1;


Doing this copies the value of
grid[0,0]
into
node
. I basically want a pointer into the
grid
array at the point specified so I can modify the Node directly. I'm unable to use
unsafe
.

Is there some syntax sugar for this or do I have to modify directly? ex:

grid[0,0].occupant = 1;

Answer

There will be syntax for that in C# 7. Right now, the only way to do that will be to pass the element by ref.

class Program
{

    static void Do(ref Node node)
    {
        node.occupant = 1;
    }

    static void Main()
    {
        Node[] nodes = new Node[10];
        nodes[5].occupant = 2;

        Do(ref nodes[5]);
        Console.WriteLine(nodes[5].occupant);

        Console.ReadLine();

    }

}

This code segment prints 1, which is the value set in the method Do. That indicates that the method has received a reference to the Node object, rather than a copied value.