johnnycrash johnnycrash - 15 days ago 9
C# Question

C# box or copy when passing structs by reference?

Does c# box a struct here?

struct S { int x; }

void foo(ref S s) { s.x = 1; }

main {
var s = new S();
foo(ref s); <-- boxing??
}


I have heard weird stuff about structs in classes. Is there boxing here? is this passing a copy of the member?

class C { S s; }

main {
var c = new C();
foo(ref c.s); <-- boxing here?? copy here???
}
void foo(ref S s) { s.x = 1; }

Answer

So Struct is value type if you read the documentation of ref

Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is NO boxing of a value type when it is passed by reference.

ref (C# Reference)

Here explanation what exactly ref is doing.

The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method.