What are the best methods: MethodReturnsBoolean == true / false OR true / false == MethodReturnsBoolean

I wrote:

if(Class.HasSomething() == true/false) 
{
  // do somthing
}
else
{
  // do something else
}

but I also saw people doing the opposite:

if(true/false == Class.HasSomething())
{
  // do somthing
}
else
{
  // do something else
}

Is there any advantage to doing one thing or another in terms of performance and speed? I am not talking about the coding style here.

+3
source share
9 answers

The second example is what I heard, called the “Yoda conditions”; "False, this method return value should be." This is not how you would say it in English, and therefore among English-speaking programmers, he usually looked down.

, . (, , ), , , "" ( , bool to bool), . , :

if(Class.HasSomething()) 
{
  // do somthing
}
else
{
  // do something else
}

, if() , , if(Class.HasSomething() == true), CLR if((Class.HasSomething() == true) == true). , , ( , , , , 2 ).

, , not if(!Class.HasSomething()) false: if(Class.HasSomething() == false). , ( , ), , false, , .

+5

,

if(Class.HasSomething())
{
  // do something
}
else
{
  // do something else
}

... .

+14

" Yoda", , , :

if (true = Foo()) { ... }  /* Compile time error!  Stops typo-mistakes */
if (Foo() = true) { ... }  /* Will actually compile for certain Foo() */

, #, , , C.


True:

if (Foo()) { ... }  

False .
!Foo(), !.

if (false == Foo()) { ... }  /* Obvious intent */
if (!Foo())  { ... }         /* Easy to overlook or misunderstand */
+9

.

if (Whatever())

, == false != true, - bool? s. ( )

+1

, IL...

+1
if(Class.HasSomething()) 
{
  // do somthing
}

- . HasSomething(). .

+1

.

if(Class.HasSomething())
{
    // do something
}
else
{
    // do something else
}

. Class.HasSomething() bool,

+1

. , type = ==. cathc, true/false

0

In the case of booleans, I would not recommend: just use if (method())and if (!method()). In the case of things other than Boolean, an agreement to use yoda-talk, for example. if (1 == x)appeared to prevent errors, because it if (1 = x)will cause a compiler error, and if (x = 1)will not (this is valid C code, but probably not the one you intended). In C #, such an operator is valid only if the variable was logical, which reduces the need for this.

0
source

All Articles