A small help in understanding structs:
I am learning how to use structs and have a question. for this question I decided to write a small test program by using some structs.
Inside Program.cs Inside Class1.cs file: Inside Class2.cs file: Am I correct in assuming that when I am calling ProcessTest method from Program.cs file, a copy of the struct object is created in memory when Class1 is being processed ? I assume that if I use a class instead of a struct for ProcessTest method, I would only be passing it as a reference to the class object and in that case, a copy of the object isn't created when Class1 is being processed
Inside Program.cs Inside Class1.cs file: Inside Class2.cs file: Am I correct in assuming that when I am calling ProcessTest method from Program.cs file, a copy of the struct object is created in memory when Class1 is being processed ? I assume that if I use a class instead of a struct for ProcessTest method, I would only be passing it as a reference to the class object and in that case, a copy of the object isn't created when Class1 is being processed
7 Replies
Yes the struct is copied
Kouhai /人◕ ‿‿ ◕人\
REPL Result: Success
Console Output
Compile: 467.630ms | Execution: 40.203ms | React with ❌ to remove this embed.
You can see here that
val
for TestClass
was modified because it was passed by by referenceIs there a performance hit by doing it like this ? would classes be a better option for this type of program ?
Depends on what you're going to do, if you're gonna box it a lot or you want the type to be mutable then go with a class, if not then a struct would be good.
Also it's recommended to keep the structs below 16 bytes.
what do you mean by box it ?
Boxing and Unboxing - C# Programming Guide - C#
Learn about boxing and unboxing in C# programming. See code examples and view additional available resources.