Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch with enum and multiple return

I have two objects:

public enum BugReportStatus
{
    OpenUnassigned = 0,
    OpenAssigned = 1,
    ClosedAsResolved = 2,
    ClosedAsRejected = 3
}

and

public enum BugReportFilter
{
    Open = 1,
    ...
    Closed = 4,
}

And I would like to create a switch case where depending on the BugReportFilter choose my output will be a specific BugReportStaus.

So I created a method CheckFilter

private BugReportStatus Checkfilter(BugReportFilter filter)
{
    switch (filter)
    {
        case BugReportFilter.Open:
            return BugReportStatus.OpenAssigned;

        case BugReportFilter.Closed:
            return BugReportStatus.ClosedAsResolved;
    }
};

The problem is that in the case of a BugReportFilter.Open option I should return BugReportStatus.OpenAssigned AND BugReportStatus.OpenUnassigned, is there a way to concat this two options in a single return ?

like image 665
Pickeroll Avatar asked May 03 '16 14:05

Pickeroll


Video Answer


3 Answers

You could return IEnumerable<BugReportStatus>:

private IEnumerable<BugReportStatus> Checkfilter(BugReportFilter filter)
{
    switch (filter)
    {
        case BugReportFilter.Open:
            return new[]{ BugReportStatus.OpenAssigned, BugReportStatus.OpenUnassigned };

        case BugReportFilter.Closed:
            return new[]{ BugReportStatus.ClosedAsResolved };
    }
};

Then you could use Enumerable.Contains to check if it's f.e. BugReportStatus.OpenAssigned:

bool isOpenAssigned = Checkfilter(someFiler).Contains(BugReportStatus.OpenAssigned);
like image 136
Tim Schmelter Avatar answered Sep 27 '22 23:09

Tim Schmelter


Make the options power of two, e.g.

public enum Flags
{
    A = 1,
    B = 2,
    C = 4
}

then return Flags.B | Flags.A from your function (the return type should be int).

Here is how to check if flag is set

bool isA = (enumFlag & Flags.A) != 0; // true means A is set

For more info, please see here.

like image 21
Giorgi Moniava Avatar answered Sep 27 '22 23:09

Giorgi Moniava


For your case, I recommend to represent the return in different bits (using concept of flags) so that you can concat the return:

public enum BugReportStatus
{
    OpenUnassigned = 1, //0000 0001
    OpenAssigned = 2, //0000 0010
    ClosedAsResolved = 4, //0000 0100
    ClosedAsRejected = 8 //0000 1000
}

Thus you could do this:

    switch (filter)
    {
        case BugReportFilter.Open:
            return BugReportStatus.OpenAssigned + BugReportStatus.OpenUnassigned; //return 3

        case BugReportFilter.Closed:
            return BugReportStatus.ClosedAsResolved;
    }

And change your return type to something like int:

private int Checkfilter(BugReportFilter filter)

And to check the result outside, simply check what flag exist in the int return

like image 27
Ian Avatar answered Sep 27 '22 22:09

Ian