Rahul Rajput
Rahul Rajput

Reputation: 1437

String class behavior

   public void main()
   {    
    string test = "testing";
    ChangeVal(test);
    Console.WriteLine(test);
   }
private void ChangeVal(string test)
{
    test = "in child";
}

If String is a class. and i pass string as a parameter to a function. change the value of that string in function. But in main function it shows the previous values. It will print testing value.

when i created Foo class which has 2 member variable integer and string. when i passed the object of the class as parameter and change value of the member variable in function. It will give updated value in the main function

public class Foo
{
    public string test = "testing";
    public int i = 5;

}

public void main()
{
        Foo obj=new Foo();
        Console.WriteLine(obj.test);
        ChangeVal(obj);
        Console.WriteLine(obj.test);
}

private void ChangeVal(Foo obj)
{
    obj.test = "in child";
    obj.i = 5;
}

If string is the class. It will update the value of the variable. May string is the sequence of Unicode character that's why it doesn't update the value in 1st case. Can any body will explain this in detail.

Upvotes: 1

Views: 124

Answers (2)

Carlos Landeras
Carlos Landeras

Reputation: 11063

Try to pass the parameter by reference to get the var updated in main thread:

private void SeString(ref string chain)
        {
            chain="new string";

        }

Then call:

string variable="hello";
SeString(ref  variable);

string output is "new string"

Upvotes: 2

Oded
Oded

Reputation: 499382

change the value of that string in function

Strings are immutable. You can't change the value of a string. You can assign another string to the same reference, but you would need to pass the reference in by using ref.

public void main()
{    
  string test = "testing";
  ChangeVal(ref test);
  Console.WriteLine(test);
}

private void ChangeVal(ref string test)
{
    test = "in child";
}

You Foo class, however, is mutable, so you can assign different values to its members.

Upvotes: 3

Related Questions