Last active
May 27, 2016 11:51
-
-
Save Phuseos/d8388f80137ce9a1e22bc1990e213c72 to your computer and use it in GitHub Desktop.
Difference null checking with If and the ?? operator in action (C#)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected void NullCheck(Object sender, EventArgs e) { | |
/* | |
* Different ways to check for a null value as an example | |
* Assume we have TextBox1 that we want to fill with a value, but only if the string is not null | |
*/ | |
//Set the value that we want to use | |
string NewMessage = null; | |
//First way to check for null, if with check, then set the TextBox value | |
if (!string.IsNullOrEmpty(NewMessage)) { | |
TextBox1.Text = NewMessage; | |
} | |
else if (string.IsNullOrEmpty(NewMessage)) { TextBox1.Text = Convert.ToString(null); } | |
//Way to check using the ?? Coalesced operator | |
TextBox1.Text = NewMessage ?? Convert.ToString(null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment