Reputation: 946
I am trying to make something like
string s = "Hello";
s.Clear();
And I created the extension method like this:
public static void Clear(this string s)
{
s = string.Empty;
}
But, when I see the value, it does not change:
I can't use ref or out because these can't be used with the keyword this. Any ideas?
Upvotes: 0
Views: 592
Reputation: 104
If the extension method checks a condition, you could pass an Action as a parameter (caller passes lambda expression) so that the action is performed only if the condition is met. That way, you avoid doing anything to the variable (even setting it to itself) unless the condition is satisfied.
Upvotes: 0
Reputation: 186668
If you're looking for a kind of mutable version of String
you can try using StringBuilder
:
StringBuilder s = new StringBuilder("Hello");
s.Clear();
...
String myFinalString = s.ToString();
Upvotes: 2
Reputation: 40516
This is not possible. From the documentation:
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.
Upvotes: 11