Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value based on multiple bool conditions

Tags:

c#

.net

I have following case:

enum values{
go = 1,
stand = 2,
jump = 3,
run = 4,
go_stand=5,
go_jump=6,
go_run=7,
go_stand_jump=8,
… and so on 
Go_stand_jum_prun=17}

int select value(bool go, bool stand, bool jump, bool run)
{
}

Based on combination of bool values passed to the method I need to return appropriate value, meaning if go=true and the rest false 1 will returned if all parameters passed in will be true 17 will be returns, the same applies for all combinations in between. The Only idea I have it’s a lot of if and else if statements to evaluate possible combinations, which is sort of ugly. The question is there more elegant solution.

Thank you all!!!

like image 891
user285682 Avatar asked Dec 04 '22 23:12

user285682


1 Answers

To achieve this you have to modify your enum

enum values {
    none = 0,
    go =  ( 1 << 0 ), // 1
    stand = ( 1 << 1 ), // 2
    jump =  ( 1 << 2 ), // 4,
    run = ( 1 << 3 ), // 8
    go_jump = go | jump
}

Then in your method:

values GetValues(bool go, bool stand, bool jump, bool run)
{
    values result = values.none;
    if( go )
        result |= values.go;

    if( stand )
        result |= values.stand;

    // and so on...

    return result;
}
like image 128
Mateusz Avatar answered Dec 24 '22 18:12

Mateusz