Auto quotes around string in c# - build in method?

Do you mean just adding quotes? Like this?

text = "\"" + text + "\"";

? I don't know of a built-in method to do that, but it would be easy to write one if you wanted to:

public static string SurroundWithDoubleQuotes(this string text)
{
    return SurroundWith(text, "\"");
}

public static string SurroundWith(this string text, string ends)
{
    return ends + text + ends;
}

That way it's a little more general:

text = text.SurroundWithDoubleQuotes();

or

text = text.SurroundWith("'"); // For single quotes

I can't say I've needed to do this often enough to make it worth having a method though...


string quotedString = string.Format("\"{0}\"", originalString);

Yes, using concatenation and escaped characters

myString = "\"" + myString + "\"";

Maybe an extension method

public static string Quoted(this string str)
{
    return "\"" + str + "\"";
}

Usage:

var s = "Hello World"
Console.WriteLine(s.Quoted())

Tags:

C#

String