Wednesday, January 7, 2009

Value Types and Reference Types Vs Passing Value by Reference And Value

Before I will go for different aspects of value and referece type it is necessary to highlight a point which become crucial for the understanding.

Very softly it sounds that Passing values by Reference or Value are similar to reference type and value type concepts but I'm sorry its not.So let's go through the basics first, Values types and reference types could be diffrentiated down like this..

Value types :
All numeric data types int,double
Boolean, Char, and Date
All structures, even if their members are reference types
Enums, since the type included inside them is always Byte, Short, Integer,Long

Reference types :
String
All arrays, even if elements contained are value types
Class types
And Delegates

Now come to CLASS Types - every object created is a Reference type.It means that if you pass it ByRef or ByVal, any changes you make to it are going to be reflected and to be
made to the object itself. I know it seems a sweeping statement, but for all reasons and purposes, it's fairly true.


So Passing a Reference type ByValue passes a copy of a pointer(memory location) to the value.While passing a value type it simply acts like it's actually passing its own data.

If you have a Reference type composed exclusively of Value Types then it will behave just like a reference type but it's members will behave like Value types.

If you pass a Structure for instance, Even if it is completely composed of Reference types, it will behave as a Value type, because after all, that's what it is.

Now what will happen if you try to copy or clone a Reference Type. Well,the short answer is that it will behave just like you'd expect a reference type to behave.

Finally I will say Reference and Value types are very very different in .NET than anything prior to it. If you don't get under the actuals and not try to understand they way they work, you are going to have it as a pain..
-
*Indigo Ocean Dreams: 4 Children's Stories Designed to Decrease Stress, Anger and Anxiety while Increasing Self-Esteem and Self-Awareness

1 comment:

  1. Nice post. Good work man, nice concept of heap and stack. Really interesting to read.

    ReplyDelete