Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension error assignment, how to fix?

Tags:

c#

.net

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?

like image 525
Denis Balan Avatar asked Dec 13 '25 05:12

Denis Balan


1 Answers

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.

like image 102
Tim S. Avatar answered Dec 15 '25 19:12

Tim S.