C# Conditional Operator versus Null-Coalescing Operator

In javascript I often use a phrase like this:

var text = tempText || “No Text Given”;

With this phrase we assign the value of tempText to the variable text. If tempText is null we assign “No Text Given” to the text variable.

To do the same trick in C# I was using the Conditional Operator:

string text = tempText != null ? tempText :  “No Text Given”;

In my opinion this isn’t very nice code. So I started searching and I found the nice Null-Coalescing Operator. It goes like this:

string text = tempText ?? “No Text Given”;

This looks much better.
For all you javascript-geeks. The javascript notation also checks for empty string. The Null-Coalescing Operator does not.

Happy coding!!

  1. No comments yet.

  1. No trackbacks yet.