Search code examples
c#arraysstructref

Get a reference to a struct inside array


I want to modify a field of a struct which is inside an array without having to set entire struct. In the example below, I want to set one field of element 543 in the array. I don't want to have to copy entire element (because copying MassiveStruct would hurt performance).

class P
{
    struct S
    {
      public int a;
      public MassiveStruct b;
    }

    void f(ref S s)
    {
      s.a = 3;
    }

    public static void Main()
    {
      S[] s = new S[1000];
      f(ref s[543]);  // Error: An object reference is required for the non-static field, method, or property
    }
}

Is there a way to do it in C#? Or do I always have to copy entire struct out of array, modify the copy, and then put the modified copy back into array.


Solution

  • The only problem is that you're trying to call an instance method from a static method, without an instance of P.

    Make f a static method (or create an instance of P on which to call it) and it'll be fine. It's all about reading the compiler error :)

    Having said that, I would strongly advise you to:

    • Avoid creating massive structs if at all possible
    • Avoid creating mutable structs if at all possible
    • Avoid public fields