0

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;
11
  • 1
    Why dont you use class instead of struct ? Commented Aug 27, 2016 at 22:07
  • Will it make a difference? Commented Aug 27, 2016 at 22:08
  • It doesn't copy in c#, It is a reference (pointer). Commented Aug 27, 2016 at 22:09
  • Does that mean every element in array has its own heap allocation? Commented Aug 27, 2016 at 22:11
  • 3
    struct is not immutable, it is rather passed to methods by value, i.e. copied unless method argument is ref. Value types are rarely a good choice, though. Examples are game programming, where array of reusable structs avoids garbage collection for entire lifetime of a game. New C# 7 syntax will address precisely that use. Commented Aug 27, 2016 at 22:24

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.