Skip to content

Instantly share code, notes, and snippets.

@Phuseos
Last active May 27, 2016 11:51
Show Gist options
  • Save Phuseos/d8388f80137ce9a1e22bc1990e213c72 to your computer and use it in GitHub Desktop.
Save Phuseos/d8388f80137ce9a1e22bc1990e213c72 to your computer and use it in GitHub Desktop.
Difference null checking with If and the ?? operator in action (C#)
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