C#: Conditional Operator ?:
Author: jason
Date: 2019-01-19 14:46:13
Category: Technical

I frequently want to set null/blank/empty things to actually be something. I also frequently forget how to properly use the ?? and ?: conditional operators... Call me forgetful...

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator

Code


public static void InLineNullReplace()
{
string a = null;
string b = "";
string c = String.Empty;
string d = "Not Empty";
int? one = null;
int two = 75;

try
{
Console.WriteLine("Replace the emptiness with something");
Console.WriteLine("String a is: " + (a ?? "Empty"));
Console.WriteLine("String b is: " + (b ?? "Empty"));
Console.WriteLine("String c is: " + (String.IsNullOrEmpty(c) ? "Also Empty" : c));
Console.WriteLine("String d is: " + (String.IsNullOrEmpty(d) ? "Also Empty" : d));
Console.WriteLine("Integer one is: " + (one == null ? default(int) : one));
Console.WriteLine("Integer two is: " + (two == null ? default(int) : two));

} catch (Exception e)
{
Console.Write(e);
}
}







jason @ jasonthomasfrance.com - www.masterstationlog.com - copyright 2009