Reputation: 1
I'm new to C# and I'm having trouble while disposing of a variable, because it seems to affect another variable that it shouldn't. A simplified version of the code is:
class Game
{
Bitmap image;
public Game(Bitmap image)
{
this.image = image;
}
}
...
Bitmap tempConvert;
...
tempConvert = new Bitmap(100, 100);
games.Add(new Game(tempConvert));
tempConvert.Dispose();
It should be pretty simple: tempconvert gets passed on to Game.image then gets disposed of. Except that tempConvert.Dispose() seems to affect Game.image as well. There's no pointers or adresses or anything, so I don't know why Game.image is affected. Removing tempConvert.Dispose() solves the problem, but creates a massive memory leak.
So then, why is tempConvert.Dispose() affecting Game.image if tempConvert's contents had already been passed on?
Upvotes: 0
Views: 58
Reputation: 22945
You are passing a reference of the Bitmap object to your Game class, not the contents of the bitmap. You create 1 Bitmap object, not more; the Bitmap object is used by your initial code and the Game object.
Therefore disposing it in your initial code will affect your Game object.
Upvotes: 2
Reputation: 591
Bitmap
is a reference type. When you pass it to new Game
, you're passing a reference to the same instance of Bitmap
. Either make another copy of the Bitmap
or have the Game
class dispose of it, depending on the desired lifecycle and where else the Bitmap
is being used.
Upvotes: 4