Exel Gamboa
Exel Gamboa

Reputation: 946

Change value using Extension Method in C# (as allowed in VB.NET)

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:

enter image description here

I can't use ref or out because these can't be used with the keyword this. Any ideas?

Upvotes: 0

Views: 592

Answers (3)

Nickadoo
Nickadoo

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

Dmitrii Bychenko
Dmitrii Bychenko

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

Cristian Lupascu
Cristian Lupascu

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

Related Questions