Home > Mobile >  String is a class so should it be by reference?
String is a class so should it be by reference?

Time:09-05

From the below code(First way) my output is "11". and the Second way output is "1199"; But as String is a class, it should be by reference and (First way) should return "1199"; Why is it not working that way?

//First way:
void StringTest()
{
    String s = "11";
    Update(s);
    Console.WriteLine(s);
}

void Update(String v)
{
    v  = "99";
}

//Second way:
void StringTest()
{
    String s = "11";
    Update(ref s);
    Console.WriteLine(s);
}

void Update(ref String v)
{
    v  = "99";
}

CodePudding user response:

For the first snippet:

void Update(String v)
{
    v  = "99";
}

As a result of = a new string will be created and assigned to the local variable, the fact that string is a reference type does not mean much here.

Also note that string's are immutable in C#:

String objects are immutable: they can't be changed after they've been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object.

  •  Tags:  
  • c#
  • Related