Slasher
Slasher

Reputation: 618

How to shorten boolean function

I have to shorten boolean function to one line. I'm a begginer in C# and I have no idea, how to shorten it.

    static bool mod(int number) 
    {
        if (number % 3 == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Upvotes: 0

Views: 515

Answers (5)

Sethu Bala
Sethu Bala

Reputation: 457

static bool mod(int number) 
{
    return number % 3 == 0;
}

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234695

Use simply number % 3 == 0, either inline, or as the function body. If you do retain it as a function then do consider renaming the function to mod_by_3 or similar.

In C and C++ you can ace it with the considerably clearer !(number % 3).

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

I'm the winner? Expression bodied functions are new in C#6

static bool Mod(int number) => number % 3 == 0;

Upvotes: 6

Oskar
Oskar

Reputation: 2083

Just return the expression inside the if-statement:

static bool mod(int number) 
{
    return number % 3 == 0;
}

Upvotes: 1

Andrea
Andrea

Reputation: 6123

You want this:

static bool mod(int number){    
   return number % 3 == 0;
}

Upvotes: 6

Related Questions