C# Syntax Shortcuts

23,902

Solution 1

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.

Solution 2

My all time favorite is

a = b ?? c;

which translates to

if (b != null) then a = b; else a = c;

Solution 3

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]

Solution 4

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

Here's another pdf.

Share:
23,902
Graham Conzett
Author by

Graham Conzett

Updated on July 02, 2020

Comments

  • Graham Conzett
    Graham Conzett almost 4 years

    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
    Graham Conzett over 14 years
    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.
  • adrian.andreas
    adrian.andreas over 14 years
    actually, that would be if b is not null, then a equals b, else a equals c