Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Replace value of original string in extension method

Tags:

c#

I am trying to author an extension method for a string that takes one argument and it appends the argument to the string's 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 like to use this 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 issue is that I am seeing this:

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

Now I have read the this! issue here on StackOverflow, and I am aware that I am doing a similar thing. I can't replace the entire value of the string, I have to modify the contents of the string that is sent through... I just can't find a way to modify it. I've tried modifying the character array and have had no luck. Any ideas?

like image 765
GingerLoaf Avatar asked Aug 23 '12 20:08

GingerLoaf


3 Answers

Strings are immutable.
That's fundamentally impossible.

like image 166
SLaks Avatar answered Sep 26 '22 01:09

SLaks


To achieve this you would have to pass this string originalValue as ref, but that's not possible. You can do so with a normal method, though:

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

but it has to be called like this:

AddNumber(ref testing, "1");
like image 37
Joey Avatar answered Sep 26 '22 01:09

Joey


You have to use this method like that:

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 this with a 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 doesn't look so efficient.

like image 36
Amiram Korach Avatar answered Sep 22 '22 01:09

Amiram Korach