i understand that in csharp "string" and "object" are reference type...
For e.g. in this case
myString is passed to a method and it changes the value of the string..
if string is a reference type, isnt it passed to the method by
reference and the second WriteLine should be "edited" instead of "hello
world" ?
String myString = "hello world";
Console.WriteLine("String before function : " + myString);
doSomethingToString(myString);
Console.WriteLine("String afer function : " + myString);
static void doSomethingToString(string myString)
{
myString = "edited";
}
Marc Gravell - 31 Oct 2006 17:05 GMT
It is a reference type passed by value; since you reassign the string this
is behaving correctly.
As always, Jon puts it better than I could:
http://www.yoda.arachsys.com/csharp/parameters.html
(sorry Jon, I always intend to use the pobox address, but google says
yoda...)
Marc
gpg - 31 Oct 2006 17:05 GMT
In C# arguments are passed by value - thus only the copy myString in
function scope is modified.
If you want to modify an argument, you must use the 'ref' keyword to
pass the argument by reference.
For example
> String myString = "hello world";
>
[quoted text clipped - 6 lines]
> myString = "edited";
> }
will result in myString being modified in the main scope.
GPG
Hans Kesting - 31 Oct 2006 17:09 GMT
> i understand that in csharp "string" and "object" are reference type...
>
[quoted text clipped - 14 lines]
> myString = "edited";
> }
No, because with the statement
myString = "edited";
you don't change the contents of the original string, but create a new
string (containing "edited") and changing the reference of the local
variable myString to point to that new string.
When you return from that function, the original reference is still in
place, so you see the original text. (Note: there are two separate
'myString' variables here: one 'global', the other local to the method)
Hans Kesting
Göran Andersson - 01 Nov 2006 00:21 GMT
> i understand that in csharp "string" and "object" are reference type...
>
> For e.g. in this case
> myString is passed to a method and it changes the value of the string..
No, actually it doesn't change the value of the string. Strings are
immutable in .NET, meaning that the value of the string object never
changes.
Instead a completely new string object is used and the reference to that
object replaces the old reference.
> if string is a reference type, isnt it passed to the method by
> reference and the second WriteLine should be "edited" instead of "hello
> world" ?
No, all parameters are passed by value by default. For a reference type
that means that the reference is passed by value, i.e. the value of the
reference is copied.
In the method you are using the copy of the reference, so eventhough you
replace the reference with the reference to the new string, that does
not change the original reference.