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?
Strings are immutable.
That's fundamentally impossible.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With