-5

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#?

Alan2
  • 23,493
  • 79
  • 256
  • 450

4 Answers4

3

Try this:

var a = myString ?? "0.0.0";

In the end it's an if statement but written differently.

user11909
  • 1,235
  • 11
  • 27
1

Would this work?

var a = mystring ?? "0.0.0";

Jon Roberts
  • 2,262
  • 2
  • 13
  • 17
1

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;
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32
-1

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";
Siavash
  • 2,813
  • 4
  • 29
  • 42
Shubham
  • 443
  • 2
  • 10
  • Why "!" when you can swap the parameters between ":" - `var a = myString == null ? "0.0.0" : myString;` – i486 Apr 24 '19 at 08:02