1

I came across a C# language feature today courtesy of ReSharper, the ?? operator. This helped make the code even more concise than my initial attempt. See below for iteration in improving lines/length/readability of code.

A first attempt could be something like..

if (usersEmail == null)
  userName = firstName;
else
  userName = usersEmail;

Refactored to..

userName = usersEmail == null ? firstName : usersEmail;

Initially I thought the above would be the most efficient/concise version, but there is a third step...

userName = usersEmail ?? firstName;

Id like to know if you have any similar examples where C# language features help with reducing lines of code and improving readability?

Matt
  • 2,600
  • 4
  • 25
  • 32

6 Answers6

4

the using block, LINQ, anonymous delegates, the list would just go on..

C# has a very nice habit of introducing features in every major release that cut down the amount of code that you have to write.

Gishu
  • 126,803
  • 45
  • 214
  • 298
3

The var keyword for implicit static typing and automatic properties are two good examples.

sepp2k
  • 341,501
  • 49
  • 643
  • 658
Douglas
  • 32,530
  • 8
  • 68
  • 88
1

This thread has a lot of gems: Hidden Features of C#? (including the one you mentioned)

Community
  • 1
  • 1
mint
  • 3,106
  • 10
  • 36
  • 51
1

Using using keyword

Giorgi
  • 28,971
  • 12
  • 82
  • 118
1

Extension methods.

Joe White
  • 87,312
  • 52
  • 206
  • 320
0

LINQ queries allowing you to express the query criteria better than a foreach loop

benPearce
  • 34,921
  • 14
  • 60
  • 93