❔ Can you modify fields in a struct?
I am working on a school project and have run into an issue. Code snippets is: https://sourceb.in/SsaOkq7M8I
This line,
game.quantityInCart++;
doesn't actually change the variable. When I print it Console.WriteLine($"{game.quantity} - {game.quantityInCart}");
it is always 0. Can variables in a struct not be modified ?9 Replies
I create the game object as:
I added
into the strruct but still doesnt work
you want class instead of struct
$refvsvalue
classes on the left, structs on the right
generally you should default to classes over structs unless you have a specific reason
this applies to assignment too
for example, when you do
Game game = games[i];
you're actually making a copy of the struct and then modifying the copy, the one in the array never gets changedohhhhh right, makes sense. im too used to how it works in java. only using structs cause we haven't got up to classes yet. thank you!
so if I use a class instead of a struct,
Game game = games[i];
will not return a copy?correct, it will reference the same object in memory
if you have any C/C++ experience variables of classes are comparable to using a pointer
I understand, thanks!
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.