Does C# have a way to &&=?

163 views Asked by At

I have several booleans I need to check and turn into a single boolean for readability:

bool myBoolean = 5 == 5 && "string" == "String" && true && false && CheckSomethingElse();

Is there a way I can break this up into multiple lines to make it more readable? I can do this:

bool myBoolean = 5 == 5;
myBoolean = myBoolean && "string" == "String";
myBoolean = myBoolean && true;
myBoolean = myBoolean && false;
myBoolean = myBoolean && CheckSomethingElse();

But I am looking for something more along the lines of this:

bool myBoolean = 5 == 5;
myBoolean &= "string" == "String";
myBoolean &= true;
myBoolean &= false;
myBoolean &= CheckSomethingElse();

However, the third code block does not do the same thing as the first/second (as far as I know). Does C# have a way to improve the readability from the first code block? Or is there some sort of a normal way to code such a boolean?

2

There are 2 answers

4
n00b On BEST ANSWER

First, I may agree with some of JK and etc. opinions about rewriting, but to actually answer your question according to SO guidelines, The correct answer is No because that operator is not defined in C# and you can not overload a new operator like that for the Boolean type.

I think the best you can get is defining an extension method for the Boolean type

  public static class BoolExtension{

    public static bool And(this Boolean first, bool second){
      first =  first && second;
      return first;
    }
     public static bool MultiAnd(this Boolean first, params bool[] others)
    {
        foreach (var b in others) first = first && b;
        return first;
    }
}

and then use it like this

bool myBoolean = 5 == 5;
myBoolean.And( "string" == "String");
myBoolean.MultiAnd("A"=="A","B"=="C","D"=="D");

As you can see, this may not help much with readability.

Some people end up implementing a Decorator pattern for the Boolean class in such cases by defining a struct/class that has a Boolean inside it and does operator overloading that you like.

10
JK. On

For readability, simply extract it out into a named method where the name of the method instantly tells you the intent:

public bool FluxCapacitorIsReady()
{
    return 5 == 5 
           && "string" == "String" 
           && true 
           && false 
           && CheckSomethingElse();
}

Now you can just call that method in your code and it is immediately clear to any reader what is going on:

if (FluxCapacitorIsReady())
    StartFluxCapacitor();

This is a concept from Clean Code: see http://cleancoders.com for more.