Albert
Albert

Reputation: 151

Variable Declaration inside an IF C#

take a look at the following code :

if( down == null || down.GetFace() != Face.None || down.GetFace() != Face.Partial )
{  
    // I called GetFace() two times
    // How can i avoid to call it two times, and still putting inside that if
}  

Thank you!

Upvotes: 0

Views: 158

Answers (2)

Oded
Oded

Reputation: 498924

Refactor to a method:

private bool IsFaceNoneOrPartial(Down down)
{
   var face = down.GetFace();

   return face != Face.None || face != Face.Partial;
}

// Your code is now:
if( down == null || IsFaceNoneOrPartial(down))
{

}

Upvotes: 1

Mohamed Abed
Mohamed Abed

Reputation: 5113

To be more maintainable and expressive first separate the null check as exceptional case

then get the result to a variable and check it.

if(down == null)
  // Some exceptional case .. return or throw exception

var result =  down.GetFace();
if(result == Face.None || result != Face.Parial)
  // Do your code here

Upvotes: 2

Related Questions