4

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.

Graham Conzett
  • 8,344
  • 11
  • 55
  • 94
  • 4
    This 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
  • 8
    Omitting 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 Answers6

11
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.

codymanix
  • 28,510
  • 21
  • 92
  • 151
11

My all time favorite is

a = b ?? c;

which translates to

if (b != null) then a = b; else a = c;
GvS
  • 52,015
  • 16
  • 101
  • 139
mr_dunski
  • 441
  • 1
  • 3
  • 10
5

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]
Yatrix
  • 13,361
  • 16
  • 48
  • 78
1

How does this C# basic reference pdf document looks to you?

Here's another pdf.

Vadim
  • 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
0

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.

Joren
  • 14,472
  • 3
  • 50
  • 54
0

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

HeathenWorld
  • 117
  • 1
  • 7