the-a-monir
the-a-monir

Reputation: 177

String is a class so should it be by reference?

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";
}

Upvotes: 0

Views: 73

Answers (1)

Guru Stron
Guru Stron

Reputation: 143088

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.

Upvotes: 5

Related Questions