Given this:
var a = myString;
What I would like to do is to set the value of a
to be "0.0.0" if the value of myString
is null.
I know I can do this with some if check but is there a cleaner way to do this in the newer versions of C#?
Given this:
var a = myString;
What I would like to do is to set the value of a
to be "0.0.0" if the value of myString
is null.
I know I can do this with some if check but is there a cleaner way to do this in the newer versions of C#?
Try this:
var a = myString ?? "0.0.0";
In the end it's an if statement but written differently.
I'll try to write many implementations:
var a = myString ?? "0.0.0";
var a = myString == null ? "0.0.0" : myString;
var a = myString is null ? "0.0.0" : myString;
var a = string.IsNullOrEmpty(myString) ? "0.0.0" : myString;
You can check the value by a IsNullOrEmpty()
method on String
class, and by a conditional operator
(?) like the following code you can set your own custom text whenever your string is null.
var a = !String.IsnullOrEmpty(myString) ? myString : "0.0.0";