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 ?
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);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With