logoalt Hacker News

_old_dude_today at 8:12 AM2 repliesview on HN

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.


Replies

kuhsafttoday at 2:50 PM

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

layer8today at 8:31 AM

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.

show 2 replies