11

Is there any difference in how the C# compiler or .NET run-time handles verbatim string literals versus using escape sequences (i.e. performance) or is it just a matter of design time style? E.G.:

var pathA = "c:\\somewhere";
var pathB = @"c:\somewhere";

I would imagine they are compiled the same and it doesn't matter, but was just curious.

Picrofo Software
  • 5,475
  • 3
  • 23
  • 37
Tom Hundley
  • 1,325
  • 9
  • 14
  • I think they are compiled in the same thing. Logically speaking why would it generate different IL? – Freeman Jan 29 '13 at 13:20

3 Answers3

19

Any difference here is limited strictly to the compiler; the IL and runtime have no concept of verbatim vs escaped - it just has the string.

As for which to choose: whichever is more convenient ;p I almost always use verbatim string literals if there are unusual characters, as that allows for multi-line strings very easily and visually.

As an interesting case:

bool areSame = ReferenceEquals("c:\\somewhere", @"c:\somewhere"); // true

which tells are they are exactly the same string instance (thanks to "interning"). They aren't just equivalent; they are the same string instance to the runtime. It is therefore impossible that they can be (to the runtime) different in any way.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3

They are exactly the same. Try to decompile the two versions with a decompiler.

It's only a matter of convenience for developers when writing it in the code.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
1

The @ sign in front of a string tells the compiler to ignore any embeded escape sequences.

string "\"" would yield a single double quote. string "\" would yield a single back slash string @"\" would yield two backslashes

One Man Crew
  • 9,420
  • 2
  • 42
  • 51