By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,506 Members | 1,876 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,506 IT Pros & Developers. It's quick & easy.

basic param passing question

P: n/a
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;
}

}
Nov 15 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Oliver <sp*************@yahoo.com> wrote:
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.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.