I was wondering if there exists somewhere a collection or list of C# syntax shortcuts. Things as simple omitting the curly braces on if
statements all the way up to things like the ??
coalesce operator.

- 8,344
- 11
- 55
- 94
-
4This might be considered a duplicate of http://stackoverflow.com/questions/9033/hidden-features-of-c. At any rate, you will find a lot of what you are looking for in that post. – HitLikeAHammer Sep 16 '09 at 22:33
-
8Omitting the curly braces on if statements is not something I consider a good practice. Readability and maintainability are more important than the number of keystrokes. Use snippets or plug-ins like ReSharper to reduce typing. – TrueWill Sep 16 '09 at 22:35
-
I agree with Rick, but if anything, this should probably be a community wiki. – Sasha Chedygov Sep 16 '09 at 22:45
-
Thanks for that post Rick, that's exactly the sort of thing I was looking for. – Graham Conzett Sep 16 '09 at 22:49
6 Answers
a = b ? c : d ;
is short for
if (b) a = c; else a = d;
And
int MyProp{get;set;}
is short for
int myVar;
int MyProp{get {return myVar; } set{myVar=value;}}
Also see the code templates in visual studio which allows you to speed coding up.
But note that short code doesn't mean necessarily good code.

- 28,510
- 21
- 92
- 151
My all time favorite is
a = b ?? c;
which translates to
if (b != null) then a = b; else a = c;
-
2actually, that would be if b is not null, then a equals b, else a equals c – Rake36 Sep 17 '09 at 01:36
c# 6.0 has some fun ones. ?.
and ?
(null conditional operator) is my favorite.
var value = obj != null ? obj.property : null;
turns into
var value = obj?.property
and
var value = list != null ? list[0] : null;
turns into
var value = list?[0]

- 13,361
- 16
- 48
- 78
How does this C# basic reference pdf document looks to you?
Here's another pdf.

- 21,044
- 18
- 65
- 101
-
Thanks, I've seen the first one and it has a few examples on there, I was just wondering if there existed a more comprehensive list out there, including some of the not so obvious ones. – Graham Conzett Sep 16 '09 at 22:47
I don't know of a precompiled list, but the C# Reference (especially the C# Keywords section) concisely contains the information you're looking for if you're willing to read a bit.

- 14,472
- 3
- 50
- 54
They are not syntax shortcuts, but snippets are great coding shortcuts. Typing prop (tab)(tab), for example, stubs out the code you need for a property.
http://msdn.microsoft.com/en-us/library/ms165392(VS.80).aspx

- 117
- 1
- 7