Pills of C#: strings

In many times people have asked me some question about strings in C#. The much quoted question is about: “What is the @ before the string?”

So, now I want try to give some pills about those strings in C#.

Just to be clear, I’m assuming that you already know a base of C# and strings operations (concats, escaping, etc.)

First concept. The string type is just an alias for the String class, this mean that you have access to all built in methods of String class (Split, StartsWith, etc.). The String class also contains the indexer access declaration inself, this mean that you can access to a string character directly with the [ ] notation.

string ElCarro = "El Carro is here";
string ElCarroUP = ElCarro.ToUpper();
char Carriage = ElCarro[2]; //strings are sequence of characters

If you want you are also able to use LINQ on a string.

Lets see the “@” what means in C# strings.

When you see a “@” before a string in C#, this means that the string is escaped by default (with the exception of “”).

string noNeed = @"good morning"  // a string literal  
string escaped = @"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"
string doubleQuote = @"""Cariage!"" fall in garbage // "Carriage" fall in garbage  

How you can see, when you use a “@” before the string, nothing change if the string hasn’t escapable characters.

The second string, instead, has the “\” character that should be escaped before the use. How you can see, with “@” we can ignore the escaping. Without it, we should escape every “\” in the string, like in the comment.

The third string show you how you can escape the “” character. You just need to write a couple of “” when you want a single double quote.

Another cool feature is the use of “$” before a string, to create an interpolated string.

With the interpolated string you can write directly in the string without the need of a string concatenation.

An example:

string tablePrefix = "dev_";
int id = 1;
string myquery = $"SELECT * FROM {tablePrefix}Users WHERE IdUser={id}";
// SELECT * FROM dev_Users WHERE IdUser=1

How you can see, you just need to write the variable in the “{ }” space (and it also apply a cast, if needed and possibile) to get the complete string.