C# basics: $pecial Ch@racters

String interpolation – $

Definition of interpolate: transitive verb

  • 1a: to alter or corrupt (something, such as a text) by inserting new or foreign matter
  • b: to insert (words) into a text or into a conversation

Source: Merriam-webster

When you want to insert code expressions in a string, using a string interpolation with the $ character in front of the string is the easiest and most readable way.

Console.WriteLine($"Car with ID {Car.CarID} costs {Car.Price}.")

Verbatim identifier – @

Definition of verbatim:

In the exact words word for wordquoted the speech verbatim

Source: Merriam-webster

The C# compiler translates some special characters in a string. For example, when writing a filepath:

//Will not compile
Console.WriteLine("C:\Program Files\Documents\");

//Compiles
Console.WriteLine("C:\\Program Files\\Documents\\");

The \ is interpreted as an escape character, for the character after it, instead of just a \ character. Especially for filepaths it’s very handy to just be able to write the path, so here you can use the verbatim identifier @ and the compiler will interpret the string verbatim, “literally”.

Console.WriteLine(@"C:\Program Files\Documents\");

Leave a comment

Design a site like this with WordPress.com
Get started