Replacing a string using an extension method

If I have a string and I want to replace the last character from this string with an asterisk, for example.

I tried this

var myString = "ABCDEFGH";
myString.ReplaceCharacter(mystring.Length - 1, 1, "*"); 

public static string ReplaceCharacter(this string str, int start, int length, string replaceWith_expression)
{
    return str.Remove(start, length).Insert(start, replaceWith_expression);
}

I tried using this extension method, but this will not work. Why is this not working?

+4
source share
2 answers

Method, since it replaces the character, but you have to catch the result

myString = myString.ReplaceCharacter(myString.Length - 1, 1, "*"); 
+8
source

The problem is that strings are immutable. Replace, substring methods, etc. Do not change the string itself. They create a new line and replace it. Thus, for the correct code to be given, it must be

myString = myString.ReplaceCharacter(myString.Length - 1, 1, "*"); 
+2
source

All Articles