C # Replace source string value in extension method

I am trying to create an extension method for a string that takes one argument and adds the argument to the string value. Here is the behavior I want:

public static void AddNumber(this string originalValue, string id) { List<string> ids = originalValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToString(); ids.Add(id); string newValue = string.Join(",", ids); originalValue = newValue; } 

Then I would use it as follows:

  string testing = ""; testing.AddNumber("1"); // value should be 1 testing.AddNumber("2"); // value should be 1,2 testing.AddNumber("3"); // value should be 1,2,3 

The problem is that I see this:

  string testing = ""; testing.AddNumber("1"); // value is "" testing.AddNumber("2"); // value is "" testing.AddNumber("3"); // value is "" 

Now I read this one ! here on StackOverflow, and I know that I am doing this. I can’t replace the whole value of the string, I need to change the contents of the string that is sent through ... I just can’t find a way to change it. I tried modifying an array of characters and no luck. Any ideas?

+6
source share
4 answers

Lines are immutable .
This is fundamentally impossible.

+17
source

To achieve this, you need to pass this string originalValue as ref , but that is not possible. You can do this with the usual method:

 public static void AddNumber(ref string originalValue, string id) 

but it needs to be called like this:

 AddNumber(ref testing, "1"); 
+6
source

You should use this method as follows:

 public static string AddNumber(this string originalValue, string id) { List<string> ids = originalValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToString(); ids.Add(id); string newValue = string.Join(",", ids); return newValue; } testing = testing.AddNumber("1"); 

But you can do it with StringBuilder :

 public static void AddNumber(this StringBuilder builder, string id) { var originalValue = builder.ToString(); if (originalValue.EndsWith(",") || string.IsNullOrEmpty(originalValue)) builder.Append(id); else builder.Append("," + id); } var testing = new StringBuilder(); testing.AddNumber("1"); testing.AddNumber("2"); testing.AddNumber("3"); 

I also changed the algorithm. It does not look so effective.

+3
source

Yes, you can do it with StringBuilder,

A simple example;

 public static void AddNumber(this StringBuilder value, int i) { value.Append(i.ToString()); } StringBuilder testing = new StringBuilder(); testing.AddNumber("1"); testing.AddNumber("2"); testing.AddNumber("3"); Console.WriteLine(testing.ToString()); //123 
0
source

Source: https://habr.com/ru/post/923592/


All Articles