← Back to context

Comment by _old_dude_

14 hours ago

The article has a section about that.

For me, a struct in C/C# can be modified and is passed by copy while a value class can not be modified and is passed by value.

I do not think you can do stack allocation in Java.

Like @layer8 said, pass by copy and pass by value are the same.

C# copies C++ behavior where you can pass a struct by value or reference, and you can mark the parameter as readonly. C# also has in/out parameters. Essentially, you can program in C# exactly like you would in C++.

https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...

The footgun with C# structs are that you can accidentally box them onto the heap. To avoid that you can define `ref struct`s that cannot be boxed. `ref struct`s follow the C# disposable pattern.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-...

https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...

I don’t see a difference between pass by copy and pass by value.

The mutability difference is that part of a struct can be modified in place, which value classes can’t: the value of a complete value-class variable (or array slot) can only be modified (reassigned) as a whole. This is presumably because object references to value-class objects can be created, and those objects should be immutable so their identity doesn’t matter.

  • I think pass by copy is a consequence of being modifiable.

    The other solution is to stack allocate and pass a pointer but as i said, unlike in C#, i do not think it's possible to do that in Java.

    In Go, you can stack allocate but when you send a pointer (that escapes), the compiler will heap allocate the object.

    • My point is that pass by copy and pass by value do the same thing, they copy the value representation. In other words, pass by copy means exactly pass by value.

      3 replies →

  • I think that's mostly a semantic difference - Java avoided the problem of strange lifetimes, captures, tearing by fixing the semantics as immutable value objects, while C# has to deal with these issues.

    But under the hood it can (and will) do a modification in place.