about the class string

T

Tony Johansson

Hello!!

I have a simple question and that is about the class Class1 below.
As I have learned the datatype string a reference type.
I set the number field to "1" in main and pass this number to method foo.
In foo I changed number to "2" but when I come back in main it's still "1".

If I use ref then number is changed also in main but as I mentioned before
because
string is a reference type I shouldn't have to use ref.

Can somebody explain why number is not "2" in main.

class Class1
{
public void foo(string number)
{
number = "2";
}

[STAThread]
public static void Main(string[] args)
{
string number = "1";
new Class1().foo(number);
}
}

//Tony
 
S

Saad Rehmani

Tony,

A 'ref' parameter has an extra layer of indirection that allows you to change
the actual reference.

Do a bit of reading up on what happens when you pass a variable by ref and
see if you can figure out why this won't compile:

public void foo(ref string s) { }
foo(ref "inline-string");.

but this will:
public void foo(string s) { }
foo("inline-string");.
 

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

Top