Monday, July 17, 2006
C# syntax: the @ symbol
a friend of mine asked me the other day what the @ symbol did in C#. He said he had looked everywhere but couldn't find an answer. And, it's true, it's not that easy to find it on the net.
anyway, for him and for you, here it is:
the @ symbol in C# is placed before a string to denote it is a literal such as "Hello I'm a string" as opposed to being like this "Hello" + var1 + var2.
so if you want to assign that literal to a variable you could write it like this:
string hello = @"Hello I'm a string";
so, what's the advantage of adding the @?Couldn't I just leave it out?
Yes you could and in this case the "@" is not doing much at all. Its power comes when you need to use characters that must be escaped in a string because once a string is marked as literal, C# will not attempt to interpret any characters in any other way than plain text so there is no need to escape special characters anymore.
for instance, if you have a path variable and you want assign it to your c drive, you would have to do:
string path = "c:\\test";
that is because the backslash is a special character and must be escaped. However, if you include the @ before the literal string then you dont' need to escape your characters anymore and then you could write it like this:
string path = "c:\test";
which is much better.
a friend of mine asked me the other day what the @ symbol did in C#. He said he had looked everywhere but couldn't find an answer. And, it's true, it's not that easy to find it on the net.
anyway, for him and for you, here it is:
the @ symbol in C# is placed before a string to denote it is a literal such as "Hello I'm a string" as opposed to being like this "Hello" + var1 + var2.
so if you want to assign that literal to a variable you could write it like this:
string hello = @"Hello I'm a string";
so, what's the advantage of adding the @?Couldn't I just leave it out?
Yes you could and in this case the "@" is not doing much at all. Its power comes when you need to use characters that must be escaped in a string because once a string is marked as literal, C# will not attempt to interpret any characters in any other way than plain text so there is no need to escape special characters anymore.
for instance, if you have a path variable and you want assign it to your c drive, you would have to do:
string path = "c:\\test";
that is because the backslash is a special character and must be escaped. However, if you include the @ before the literal string then you dont' need to escape your characters anymore and then you could write it like this:
string path = "c:\test";
which is much better.
