C
C#2y ago
corey

❔ 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
corey
coreyOP2y ago
I create the game object as:
Game game = new Game()
{
gameId = int.Parse(data[0]),
platform = data[1],
rating = data[2],
type = data[3],
quantity = int.Parse(data[4]),
price = double.Parse(data[5]),
title = data[6],
quantityInCart = 0
};
games.Add(game);
Game game = new Game()
{
gameId = int.Parse(data[0]),
platform = data[1],
rating = data[2],
type = data[3],
quantity = int.Parse(data[4]),
price = double.Parse(data[5]),
title = data[6],
quantityInCart = 0
};
games.Add(game);
I added
public void IncrementQuantityInCart()
{
quantityInCart = quantityInCart + 1;
Console.WriteLine(quantityInCart);
}
public void IncrementQuantityInCart()
{
quantityInCart = quantityInCart + 1;
Console.WriteLine(quantityInCart);
}
into the strruct but still doesnt work
Cattywampus
Cattywampus2y ago
you want class instead of struct
Jimmacle
Jimmacle2y ago
$refvsvalue
Jimmacle
Jimmacle2y ago
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 changed
corey
coreyOP2y ago
ohhhhh 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?
Jimmacle
Jimmacle2y ago
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
corey
coreyOP2y ago
I understand, thanks!
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server