Tuesday, June 25, 2013

Curly braces in C# string.Format()

That awkward moment you discover you don't know how to escape the curly braces inside the formatter string in the string.Format() method in C#. That's right, I've been using this method for at least two years now, and I was never confronted with this situation. Well, it's fairly easy to go around the problem, just use double braces {{ or }} and you'll get something like the following:

String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name)

Info

The @ sign in C#

The @ symbol serves 2 purposes in C#:
#1 allows you to use a reserved keyword as a variable like this:
int @int = 15;
#2 lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
var myString = "c:\\myfolder\\myfile.txt"
alternatively you can do this:
var myString = @"c:\myFolder\myfile.txt"
Info