Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change struct in method

Tags:

c#

.net

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.

like image 518
gruber Avatar asked Oct 21 '25 07:10

gruber


1 Answers

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.

like image 163
Julien Roncaglia Avatar answered Oct 23 '25 22:10

Julien Roncaglia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!