tags:

views:

424

answers:

1

I have an Enum, suppose:

public enum ItemStatus {
    Available, Unavailable
}

I have a method that returns a list of those TVs, based on a filter. And a filter is represented by an Enum:

[Flags]
public enum ItemStatusFilter {
    Available = 1, Unavailable = 2
}

Question: what is a slick way to check if given instance of ItemStatus matches given instance of ItemStatusFilter?

I dislike the idea of assigning values to ItemStatus members (1,2) since it is not required by that enum. Right now my code looks as follows:

public static bool Matches(this TagStatusFilter statusFilter, TagStatus status) {
  if (status == TagStatus.Available && ((statusFilter & TagStatusFilter.Available) != 0)) return true;
  if (status == TagStatus.Unavailable && ((statusFilter & TagStatusFilter.Unavailable) != 0)) return true;
  return false;
}

What about something along these lines?

[Flags]
public enum TagStatusFilter {
    Available = 1 << TagStatus.Available,
    Unavailable = 1 << TagStatus.Unavailable
}

The goal is to reduce amount of code, and reduce coupling between types.

Does it feel like enum TagStatusFilter is misused here?

A: 

i don't like it.. but it'll work:

        foreach (tv t in tvs)
        {
            if (isf.ToString().Contains(t.Status.ToString()))
            {
                //match
                Console.WriteLine("matched");
            }
        }
Sk93
That may return false positives if one enum member name is also a substring of another member.
Mattias S
not in this instance, as the first letter of the enum is capitalised.Caution is obviously advised, and I do say I don't like it.. but it will definately work in THIS instance :)
Sk93