String variable as parameter!

  • Thread starter Thread starter Gigsman
  • Start date Start date
G

Gigsman

public void Foo(string one)
{
one = "two";
}


main()
{
string one = "one";
Foo(one);
Console.writeline(one);
}

What is return result? String variable 'one' is "one" or "two"?


thanks!

--Tony
 
As it stands, "one" will be written to the console.

(warning: slightly confusing terminology ahead; read slowly...)
normally for reference types (such as the string class) the *reference* to
the object is passed *by value*; by *reassigning* (one = "two"), you break
this relationship. Note that if instead you had the below you would see
"two", since we haven't *reassigned* the variable (we have just changed
properties of the referenced item):
class SomeClass {
public string Text;
}
public void Foo(SomeClass one)
{
one.Text = "two";
}
main()
{
SomeClass one = new SomeClass();
one.Text = "one";
Foo(one);
Console.writeline(one.Text);
}
===
equally, if we used "ref string one" as the parameter (and called via
"Foo(ref one)") then our reassignment would be reflected in our calling
code.

Marc
 
Hi,

Dont you think you would have get a faster , 100% correct answer by just
running it?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top