Dim myString As String = "test string"
Dim hash1 As New Hashtable
Dim hash2 As New Hashtable
hash1.Add(0, myString)
hash2.Add(0, myString)
Console.WriteLine("Hash1={0} Hash2={1}", CType(hash1(0), String), CType(hash2(0), String))
myString = "Did it change"
Console.WriteLine("Changed string")
Console.WriteLine("Hash1={0} Hash2={1}", CType(hash1(0), String), CType(hash2(0), String))
Console.ReadKey()
@ Architect - I think you are right, but I’m not sure how to test it.
@ Jas - I agree with @ Architect, once you reassign a value to a string it will no longer point to the same object. Strings are unique that way, in that they are both a reference type and a value type.
In my application I need to create many dozens of objects that contain constant strings that are identical to each other, and I want to minimize the memory used.
Yes, but I don’t think that’s the root of the problem with Hashtables. If you notice, the Add() takes an “object” type parameter. This means that whatever type you send it is going to be cast to an immutable type. Change “myString” in Jas’ example to an int type which is normally mutable and you’ll get the same result.
If you need a mutable collection then use a Dictionary<key,val> type or an array. A Dictionary<> where the key is equal to the hash value of the type would more or less give you the same thing as a Hashtable although performance may not necessarily be quite equal. It would be interesting to compare.
@ Ian - please explain further. Would you agree that both hashtables will contain references to the original string, or will they end up with their own immutable copy?
Calling functionX does not change the value of stringA, but calling functionY does.
In functionX, a copy of the reference was put into the stack and passed to the function. When you changed the value of x, you changed the value on the stack.
In functionY, by using the ref modifier, you told the compiler you did not want a copy of the reference on the stack. You wanted the function to directly access the reference for reading and writing.
It doesn’t demonstrate that. Mike is right. References in both cases.
As for Jas’s example. In both cases strings are passed as references. In first case another variable is created that references the same string. In second original variable is used.