In your opinion, what is more readable: ?? (operator) or using if

I have a method that will get string, but before I can work with it, I need to convert it to int. Sometimes it can be null, and I need to change its value to "0". Today I have:

public void doSomeWork(string value)
{
   int SomeValue = int.Parse(value ?? "0"); //it can throw an exception(i know)
}

I did this, but my boss asked me to reorganize it:

public void doSomeWork(string value)
{
    if(string.IsNullOrEmpty(value))
        value = "0";
    int SomeValue = int.Parse(value);
}

In your opinion, what is the best option?

+3
source share
13 answers

- , - , , , , "" ?? null.

- :

public int doSomeWork(string value) {
  int someValue = 0;

  if (!string.IsNullOrEmpty(value)) {
    Int.TryParse(value, out someValue);
  }
}

, " ".

+5

TryParse()?

public int doSomeWork(string stringValue)
{
    int value;
    int.TryParse(stringValue, out value);

    return value;
}

0, .

, , . int . , . , ( ...).

+11

, - , , ! , , .

int someValue = int.Parse(value ?? "0");
+3

(??) if. , , FAR . #, -, LINQ- .. , , /.

+2

"0" 0? :

public int doSomeWork(string value) {
   int someValue;
   if (String.IsNullOrEmpty(value)) {
      someValue = 0;
   } else {
      someValue = Int32.Parse(value);
   }
}
+2

public int doSomeWork(string value)
{
   int result = 0; //default?

   if(string.IsNullOrEmpty(value))
   {
      result = 0;
   }
   else
   {
      result = int.Parse(value); //you could also consider using TryParse(...) if your string could possibly also be different from a number.
   }

   //do some calculations upon "result"


   return result;
}

( ), , , , "" .

+2

. ( if(string.IsNullOrEmpty(value)), , , ?? .

, . .

+1

int someValue = string.IsNullOrEmpty()? 0: int.Parse();

+1

value == null, , value == string.Empty || value == null. , , .

+1

var = 0; int.TryParse( yourString, out);

( )

+1

, . ** , , string.IsNullOrEmpty **

, if . , . . , .

public int doSomeWork(string value)
{
  return int.Parse(value ?? "0");
}



public int doSomeWork(string value)
{
   if(value == null)
      value = "0";
    int SomeValue = int.Parse(value);
    return SomeValue;
}
0

-? !

, #, .

0

[, null, , ]

, ?? , if - . " ", . , if ; , if , , , .

??, .

0

Source: https://habr.com/ru/post/1715923/


All Articles