3

How can I change struct in external method ?

public void ChangeStruct (MyStruct myStruct) {
   myStruct.field1 = 10;
   return;
}

When I pass struct to ChangeStruct method after that method I would like myStruct to be changed.

Gabe
  • 84,912
  • 12
  • 139
  • 238
gruber
  • 28,739
  • 35
  • 124
  • 216

3 Answers3

9

You need to pass a reference to the struct instead of a copy using the ref keyword :

public void ChangeStruct (ref MyStruct myStruct)
{
   myStruct.field1 = 10;
}

ChangeStruct(ref someStruct);

Your current code create a full bit-for-bit copy of the struct before entering the method and it's this copy that you are modifying, the ref keyword force the caller to pass a reference (managed pointer) to the structure instead of the copy.

Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
5

You can use the ref keyword to observe changes to structs, but in the grand scheme, you will be in a world of less hurt if you simply use a class.

For an idea on when to use or not use structs, you might consult this link. A quick snippet that you may find helpful:

Do not define a structure unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (integer, double, and so on).
  • It has an instance size smaller than 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
2

Structs are value types, you must use the ref keyword to prevent copying. Using ref and out is not recommended, see When is using the C# ref keyword ever a good idea?.

Community
  • 1
  • 1
Julius
  • 946
  • 1
  • 10
  • 26