Malcolm Smart wrote:
Like CG said, they are by ref, by default. Both instances will change.
Yes, but as you pointed out, passing the parameter with "ref" allows you to change the reference itself - which is different from changing the object being referenced. In your example, both methods only change the object being referenced, and there is no difference in that case. My point was passing reference types for "ref" has a different meaning than passing them without "ref". And strings don't behave differently - strings are immutable reference types. In your example,
static void changeMyString1(string myString)
{
myString = mystring + " worked";
}
static void changeMyString2(ref string myString)
{
myString = mystring + " worked";
}
the second method takes myString by ref, and therefore changes the reference itself. After both methods have executed, mystring will be referring to a new string object with " worked" concatentated. By passing myString as ref in the second method, the "original" myString that was passed to changeMyString2 changes to refer to the new string object. The first method doesn't take myString by ref, and therefore the original myString passed doesn't change. If you know C++, the following piece of code demonstrates the difference.
int global = 10;
void Test()
{
int val = 0;
int *p = &val;
Method2(p); // *p = 0;
Method1(&p); // *p = 10
}
void Method1(int **p)
{
*p = &g;
}
void Method2(int *p)
{
p = &g;
}
You can consider p to be equivalent to a reference type. Method2 is equivalent to not passing with "ref", and Method1 is equivalent to passing with "ref". Changing p inside Method2 doesn't affect p in Test, but changing *p in Method1 does.
Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro