views:

96

answers:

3

I migrate between C++ and VB.NET in my coding ventures... which leads to the occasional confusion about when something is by value or by reference in VB.NET.

Let's say for example that I have an array of MyObject which is populated with a bunch of objects.

dim MyArr(5000) of MyObject

Now let's say that the information from this array travels throughout various data structures:

dim MyList as new List(of MyObject)
for i as integer = 0 to 5000 step 1000
  Mylist.add(MyArr(i))
next

then

dim MyTable as new HashTable
dim i as integer = 0
for each O as MyObject in Mylist
  if i mod 2 = 0 then
     MyTable.add(O.ToString(), O)
  end if
next

Under the above scenario, I believe everything is by reference. If I extract an entry from "MyTable" and modify its MyObject Members, I think that the original in MyArr will be modified.

However, I have run into situations where I thought something was by reference, and it was by value.

Are items always added to containers by reference, or are they sometimes added by value?

I'm confused.

+2  A: 

You can use this rule: if you can assign null into object, then it will be passed by reference. Otherwise it will be passed by value.

Exception to this rule are Nullable types and structs. They are always passed by value.

Alex Reitbort
Please don't confuse "pass by reference" with "pass reference by value". See http://pobox.com/~skeet/csharp/parameters.html
Jon Skeet
+4  A: 

It's not a case of "by reference" or "by value" really. The value you pass in to the Add method is copied. However, for reference types that value is a reference to an object - and if you manipulate that object via other references to it, you'll be able to see those changes however you get to the object.

If you ever see independent copies of the data itself, that suggests you're using a value type... but if you're making changes, that suggests you're using a mutable value type, which is a bad idea. Value types should almost always be immutable, otherwise it leads to a lot of confusion. (Reference types can be immutable too - string is a good example.)

For more on reference types and value types, see my articles on references and parameters. They're written from a C# perspective, but the fundamentals apply to VB as well.

I think once you understand the distinction between a value type value and a reference, collections will make more sense to you.

Jon Skeet
Thanks, I'll have a look.
hamlin11
Typo? it should be "Reference types can be **IM**mutable too - string is a good example"
MarkJ
@MarkJ: Thanks, fixed :)
Jon Skeet
+1  A: 

I think it depends on type of items. Not on collections.

E.g.:

int[] ints = new int[10];

ints[0] = 1; //-)

in this case 1 will be copied as long as it's ValueType.

Trickster