Patrick Lorio
Patrick Lorio

Reputation: 5668

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;

Upvotes: 0

Views: 75

Answers (2)

Zoran Horvat
Zoran Horvat

Reputation: 11311

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.

Upvotes: 3

Serge Semenov
Serge Semenov

Reputation: 10062

void DoStuff( ref Node n)
{
    n.occupant = 1;
}
...
DoStuff( ref grid[0,0);

Upvotes: 1

Related Questions