Double If Else Problem in C #

I constantly find that I am writing similar code, as in the example below:

if (object["Object Name"] != null) {
    if (object["Object Name"] == "Some Value") {
        // Do Statement A
    } else {
        // Do Statement B
    }
} else {
    // Do Statement B
}

The problem is that I checked a lot whether the object is null or not, and then I can check it for the actual contents.

Statement B is always the same, and in my case it is usually an SQL statement.

Should there be a better way around this?

Thanks
Steven

+3
source share
5 answers

C # has a short circuit so you can:

if(null != object && object.name == foo)
  do A
else
  do B

C # always first evaluates the first expression in the conditional expression, and if that fails, it does not try anything else in this part of the statement.

, , , , , , . -

if(trivial comparison && trivial comparison && REALLY EXPENSIVE OPERATION)

.

+23

# , . :

if (object["Object Name"] != null && object["Object Name"] == "Some Value") 
{
    // Do Statement A
} 
else 
{
    // Do Statement B
}
+1

, if-then-else - B.

if ((object["Object Name"] != null) && (object["Object Name"] == "Some Value")) 
{
    // Do Statement A
} 
else 
{
    // Do Statement B
}
+1

? , :

if(object["Object Name"] == "Some Value") {
    // Do statement A
} else {
    // Do statement B
}

, , , , .

EDIT: , :

if (object != null) {
    if (object["Object Name"] == "Some Value") {
        // Do Statement A
    } else {
        // Do Statement B
    }
} else {
    // Do Statement B
}

:

if(object != null && object["Object Name"] == "Some Value") {
    // Do Statement A
} else {
    // Do Statement B
}
+1

: .

, , . - : ( )

private bool IsNullCheck(string objectName)
{
  if (object["Object Name"] != null)
     return false;
  else
     // statement B
}

if (!IsNullCheck("Object Name") && if(object["Object name"] == "Value") {
   // stuffs

} 
else 
{
        // Do Statement B
}

Or the like.

0
source

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


All Articles