Conditional And Null-Coalescing Operators (?: And ??)
Join the DZone community and get the full member experience.Join For Free
In code you want to assign one variable to another, but only if the variable is not null. If it is null, you want to populate the target variable with another value. The code normally may look like this using the C# Conditional Operator:
string fileName = tempFileName != null ? tempFileName : "Untitled";If tempFileName is not null, fileName = tempFileName, else fileName = â€œUntitledâ€œ. This can now be abbreviated as follows using the Null-Coalescing Operator:
string fileName = tempFileName ?? "Untitled";The logic is the same. If tempFileName is not null, fileName = tempFileName, else fileName = â€œUntitledâ€œ. The Null-Coalescing Operator comes up a lot with nullable types, particular when converting from a nullable type to its value type:
int? count = null; int amount = count ?? default(int);Since count is null, amount will now be the default value of an integer type ( zero ). Eclipse IDE and Eclipse
Opinions expressed by DZone contributors are their own.