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.
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.
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.
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.
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?.