3

Similarly to passing a list through a function and adding elements to it, I want to pass a string and add characters to it. However, I do not want to change the reference.

Func(List myList) {
  myList.Append("hello");
}
Func(List myList) {
  myList = new List();
}

It's like the distinction between the two functions above. In one case you're adding an element to an existing reference to an object, in the other case you are changing the object that is referenced to.

With strings, I have noticed you always(?) change the object that is referenced to. Every solution i've found takes two or more strings, adds them together and returns a new string.

  • Is there a way to use the same string instance and add one or more characters to this specific instance?
Zen Zac
  • 136
  • 1
  • 9
  • 7
    `string` is immutable, use a `StringBuilder` for that – Pavel Anikhouski Dec 23 '19 at 11:48
  • 2
    With `string`? No. It's immutable, you cannot change it after you've created it. Appending characters will always construct a new string. Instead, as @PavelAnikhouski comments, use a `StringBuilder`, which *can* change its contents. – Lasse V. Karlsen Dec 23 '19 at 11:50
  • Then u need `StringBuilder` as @Pavel Anikhouski said, and u can go that way alloc bytes u can say max string is 50 then alloc 50 byte (if it's not Unicode char) and then bytes => string. i know it's looks crazy way but will work :D. – CorrM Dec 23 '19 at 11:51
  • Can you provide some more info about what exactly you want to achieve? What does your outer code look like? How do you want to call this, and why is it important that the object does not change? – Kjartan Dec 23 '19 at 12:07

3 Answers3

1

Is there a way to use the same string instance and add one or more characters to this specific instance?

No, but you can do it by using StringBuilder. Pass instance of StringBuilder to a function and append any string to it, it will add string but will refer to same instance of StringBuilder class

public void AppendString(StringBuilder sb) {
  sb.Append("hello");
}

This is because string type is mutable, whenever you assign new value to string it creates new string object in memory, but StringBuilder is immutable, it is reference type. StringBuilder modifies without creating new object.

You can try below code,

public static void Main()
{
    StringBuilder sb = new StringBuilder("Default Text");
    Console.WriteLine($"Before function call: {sb.ToString()}");
    AppendString(sb);  //Function call
    Console.WriteLine($"After function call: {sb.ToString()}");
}

public static void AppendString(StringBuilder sb)
{
    sb.Append(" Hello world");
    Console.WriteLine($"Inside function: {sb.ToString()}");
}

Output:

Before function call: Default Text
Inside function: Default Text Hello world
After function call: Default Text Hello world

.Net fiddle


I would suggest you to read string vs StringBuilder

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
1

With strings, I have noticed you always(?) change the object that is referenced to.

Because strings are immutable. You can't change a string in .NET. That opens the door to many optimizations (such as string interning), but also has performance issues when you want to build a long string by parts - many allocations and copyings of memory (to concatenate two strings, you have to allocate a third in the length of the two together, then copy them).

So Microsoft created System.Text.StringBuilder. The idea is to create mutable string. The basic methods are Append() (which appends some data, often primitive types) and AppendFormat() (similar to string.Format()). Then you get a normal string by calling to ToString():

void Func(StringBuilder s)
{
    s.Append("Hi everyone!");
}

var s = new StringBuilder();
s.Append("a StringBuilder.");
Func(s);
s.ToString(); // "a StringBuilder.Hi everyone!"

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
0

You can achieve this by passing string parameter as reference. Please refer to the following code snippet.

    static void Main(string[] args)
    {
        string input = "input";
        AddString(ref input);
        System.Console.WriteLine(input);
    }

    private static void AddString(ref string input)
    {
        input += "_edited";
    }

You will need to use ref keyword in both the cases while defining and passing method parameter. Hope it helps.

Mahesh Nepal
  • 1,385
  • 11
  • 16