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]
Author by
Graham Conzett
Updated on July 02, 2020Comments
-
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 over 14 yearsThanks, 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 over 14 yearsactually, that would be if b is not null, then a equals b, else a equals c