basic param passing question

  • Thread starter Thread starter Oliver
  • Start date Start date
O

Oliver

I'm an expert C# programmer (honest) but...

the following code prints 'Oranges', not 'ORANGES' - this confuses me
because I thought reference types (eg string) where passed
by...err..reference - so changing where the reference points to in a
method ought to change the behaviour outside the method.

....using the 'ref' keyword makes this happen.
it's almost as if references passed to methods are *copied*.

so - what's going on here, and why aren't all reference types passed
by reference by default....?

thanks,
Oliver.



class Class1
{

static void Main(string[] args)
{
string fruit = "Oranges";
DoSomeWork(fruit);
Console.WriteLine("fruit: " + fruit);
}

private static void DoSomeWork(string myString)
{
string newString = myString.ToUpper();
myString = newString;
}

}
 
Oliver said:
I'm an expert C# programmer (honest) but...

the following code prints 'Oranges', not 'ORANGES' - this confuses me
because I thought reference types (eg string) where passed
by...err..reference - so changing where the reference points to in a
method ought to change the behaviour outside the method.

No. Reference type values are passed by value by default, just as value
type values are passed by value by default. It's just that a reference
type value *is* a reference, not a full-blown object itself.

See http://www.pobox.com/~skeet/csharp/parameters.html
...using the 'ref' keyword makes this happen.
Yup.

it's almost as if references passed to methods are *copied*.

It's not almost as if, that's exactly what happens.
so - what's going on here, and why aren't all reference types passed
by reference by default....?

Why should they be? Personally I think that would cause far more
confusion than the current system - especially if value types were
still passed by value by default. Do you really *want* every method to
have to declare that a string parameter should be passed by value, just
so that the caller can rely on its own variable's value not being
changed?

(Also note that there are type problems in terms of passing things by
reference - you can't pass the a string variable by reference to a
method declared as taking an object, for instance, because the method
could very well set the value to something other than a string, which
would break type safety.)
 
Back
Top