Geeks With Blogs

News

Viktor Bergman .Net für alles

As I've mentioned in an earlier post; one of my aims with this blog is NOT to talk about really advanced topics but instead I will try and reach out to all you beginners. Surely I will write about advanced stuff as I go along but now it is MY blog so I will write whatever the heck I want to :D.

So, referencetypes is the meal for the night.
The concept of referencetypes was fascinating for me back when I actually realized the definition of it, since it has such an impact on the quality of your code and how the whole "eco-system" works. Once you have begun to understand referencetypes and valuetypes, you will want to understand heap vs. stack and how the garbagecollector works. I can honestly say that I am still not 100 % on the heap vs. stack, but I'll get there :P.

Let's start off by reading some code:

Dim MyBitmap As New Bitmap(256, 256)

The New keyword creates a new instance of the object in the Heap, for which MyBitmap is a reference to. MyBitmap is not the object, it is a reference. Hence, the common exception "Reference not set to an instance of an object" that you get from having references pointing to something that does not exist.
What many programmers are afraid of, I've been there, is writing code like this:

Dim MyBitmap As New Bitmap(256, 256)
Dim MySecondBitmap as Bitmap = MyBitmap
Dim MyThirdBitmap as Bitmap = MyBitmap

Although there are three bitmap variables they are still exactly equal. If you go and change any value in MySecondBitmap you will have the same value in MyThirdBitmap since the variables are just references to something that you have created in memory. Having code like that would be completely meaningless since you only use a single object…but you get the idea :D. A common scenario is when you are passing around objects to different methods and subclasses.

Having this said, creating deeply nested relations to references and changing properties like crazy is often very errorprone. It is easy to think "Hey I will have MySecondBitmap being the same as MyBitmap at first, but later I want to change MyBitmap since they cannot be the same since they have different names."
Whilst there can be some stepping-in difficulties with this, as soon as you begin understand the flow of objects and references you will be able to write much better code where you utilize all your resources in an efficient way.

So what parts in .net are referencetypes? Classes, Interfaces, Arrays and Collections are all referencetypes. Whereas integers, enums and structs are all valuetypes…the complete opposite.

 

More about that another time J

Posted on Monday, April 2, 2007 7:08 PM Programming languages , OOP | Back to top


Comments on this post: Referencetypes… for dummies

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Viktor Bergman | Powered by: GeeksWithBlogs.net