3

We suppose that for example i have a string, and i want to escape it, and to be well reading)

need a working extension what will solve this problem

i tried.

var t = "'";
t.Escape();// == "%27" (what i need), but it not assign result to var. t
t = t.Escape();//works, but ugly.

and the extension

public static string Escape(this string string_2)
    {
        if (string_2.HasValue())
            string_2 = Uri.EscapeDataString(string_2);
        return string_2;
    }

how to fix this extension be working?

Daniel
  • 197
  • 2
  • 16

2 Answers2

5

t = t.Escape(); is the usual idiom in .NET for changing a string. E.g. t = t.Replace("a", "b"); I'd recommend you use this. This is necessary because strings are immutable.

There are ways around it, but they are uglier IMO. For example, you could use a ref parameter (but not on an extension method):

public static string Escape (ref string string_2) { ... }
Util.Escape(ref t);

Or you could make your own String-like class that's mutable:

public class MutableString { /** include implicit conversions to/from string */ }
public static string Escape (this MutableString string_2) { ... }

MutableString t = "'";
t.Escape();

I'd caution you that if you use anything besides t = t.Escape();, and thus deviate from normal usage, you are likely to confuse anyone that reads the code in the future.

Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122
1

"Mutable string" in C# is spelled StringBuilder.

So you could do something like this:

public static void Escape(this StringBuilder text)
{
    var s = text.ToString();
    text.Clear();
    text.Append(Uri.EscapeDataString(s));
}        

But using it wouldn't really be that great:

StringBuilder test = new StringBuilder("'");
test.Escape();
Console.WriteLine(test);

The real answer is to use the "ugly" string reassignment

t = t.Escape();//works, but ugly.

You'll get used to it. :)

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276