Reputation: 1600
if I had the string : string a = "Hello there"
I wish I could do : a.ReplaceThereSubstring()
and to expect a = "Hello here"
I tried like this:
public static class ChangeString
{
public static string ReplaceThereSubstring(this String myString)
{
return myString.Replace("there","here");
}
}
but it always returns null.
Upvotes: 0
Views: 159
Reputation: 15941
You cannot modify an existing string because strings are immutable.
So an expression like myString.Replace("there", "here");
will not alter the myString instance.
Your extension method is actually correct but you should use it in this way:
a = a.ReplaceThereSubstring();
Upvotes: 2
Reputation: 23087
in that case you should do this to run your code:
string a = "Hello there"
a = a.ReplaceThereSubstring();
You can not replace string's value in extension method because strings are immutable
Upvotes: 2
Reputation: 56697
You need to assign the result, of course:
string b = a.ReplaceThereSubString();
Upvotes: 1