gazeranco gazeranco - 3 months ago 9
C# Question

What is the syntax for IF AND OR C#

I am trying to do IF (SOMETHING && NOT) OR (SOMETHING && NOT)... but it is not working, can you see what I have done wrong?

if (MyBeam.Position.Rotation == Position.RotationEnum.FRONT &&
!(MyBeam.Profile.ProfileString.Contains("RHS")
|| MyBeam.Profile.ProfileString.Contains("CHS")
|| MyBeam.Profile.ProfileString.Contains("MET")
|| MyBeam.Profile.ProfileString.Contains("SHS")

||

(MyBeam.Position.Rotation == Position.RotationEnum.BACK &&
!(MyBeam.Profile.ProfileString.Contains("RHS")
|| MyBeam.Profile.ProfileString.Contains("CHS")
|| MyBeam.Profile.ProfileString.Contains("MET")
|| MyBeam.Profile.ProfileString.Contains("SHS")))))


Ignore the references to an API there but I am sure it still makes sense.

Answer

You have your parentheses wrong. This one should work:

if ((MyBeam.Position.Rotation == Position.RotationEnum.FRONT &&
     !(MyBeam.Profile.ProfileString.Contains("RHS") || 
       MyBeam.Profile.ProfileString.Contains("CHS") || 
       MyBeam.Profile.ProfileString.Contains("MET") || 
       MyBeam.Profile.ProfileString.Contains("SHS"))) ||
    (MyBeam.Position.Rotation == Position.RotationEnum.BACK &&
     !(MyBeam.Profile.ProfileString.Contains("RHS") || 
       MyBeam.Profile.ProfileString.Contains("CHS") || 
       MyBeam.Profile.ProfileString.Contains("MET") || 
       MyBeam.Profile.ProfileString.Contains("SHS"))))

That said, it's very unreadable. Try combining some of those into variables, e.g.:

bool profileCheck = MyBeam.Profile.ProfileString.Contains("RHS") || MyBeam.Profile.ProfileString.Contains("CHS") || 
                    MyBeam.Profile.ProfileString.Contains("MET") || MyBeam.Profile.ProfileString.Contains("SHS");

if ((MyBeam.Position.Rotation == Position.RotationEnum.FRONT && !profileCheck) ||
    (MyBeam.Position.Rotation == Position.RotationEnum.BACK && !profileCheck))

In this form I can see that it can be simplified:

if (!profileCheck && (MyBeam.Position.Rotation == Position.RotationEnum.FRONT || MyBeam.Position.Rotation == Position.RotationEnum.BACK))
Comments