views:

7

answers:

1

I've always been confused/unsure about how .Net copies references. Let's say I have a Bitmap object for GDI+.

dim foo as new bitmap("c:\foo.bmp")

'Foo' holds the bitmap object. Now let's say I do this.

dim bar as bitmap = foo

Is this a shallow copy or a deep copy? If I set foo equal to nothing, does bar suddenly reference 'nothing' as well? Or does bar contain a copy of the bitmap as well, and in order to remove the bitmap from memory completely, I need to set both 'foo' and 'bar' to nothing?

I need to keep a library of bitmaps in memory, and to me it would be easier to just store a reference to each bitmap in each created object as a variable, instead of coding it with an index and having to refer to the library each time it is needed (such as 'BitmapLibrary.Singleton.getBitmap(id)')

In a nutshell, can I do this:

struct graphic object
    dim myBitmap as bitmap

    sub draw(g as graphics)
          g.drawimage(myBitmap)
    end sub

instead of this:

struct graphic object
    dim myBitmapIndex as integer

    sub draw(g as graphics)
          g.drawimage(bitmaplibrary.getImage(myBitmapIndex))
    end sub
A: 

In general, references to objects just copy the reference. This is not true for types which inherit from System.ValueType, where it is copied.

For example:

Dim foo as new Bitmap("C:\foo.bmp")
Dim bar as Bitmap = foo

''//Now close foo
foo.Dispose()
''//Access to bar fails, since the object it was pointing to was the same as foo
Console.WriteLine(bar.PixelHeight)

For System.ValueType descendants:

Dim p1 as new Point(1, 2)
Dim p2 as Point = p1

p1.Offset(1, 0)

Console.WriteLine(p1)  ''//Prints (2, 2)
Console.WriteLine(p2)  ''//Prints (1, 2)

If I set foo to Nothing, then I've just made the reference point to something else (Nothing) and haven't changed the object which bar references.

If you are storing a list of objects, storing them in a list structure seems most prudent. However, if you know that you are only going to ever have a fixed, small number of objects, then perhaps keeping the references as fields of a class is a viable option. In your case, you abstract access through the method getImage which is a good design choice, since then users of your class won't have to bother knowing your strategy for keeping track of references, and you should be able to change it as needed without breaking objects which depend on your class.

codekaizen
OK, so I get it now! If I set foo to nothing, I'm just destroying the reference and not the object. However, if I perform an action on the object via a reference, like Foo.Dispose(), then I destroy the object but not the variables pointing to it. Well, it makes sense in my head anyway. Thank you!
Jeffrey Kern