ammisom
ammisom

Reputation: 49

Is there a way to enter all cases in a switch statement?

I'm working with a switch statement that sets certain properties of an object dependent on a case - a new requirement has came in to add a case statement 'All' to essentially execute all the cases to apply all the fields - used in exceptional cases.

I can't really find a nice solution around this, each case statement is only setting 1-2 property values so it wouldn't be worth separating the logic into methods. However, I also don't want to have a load of duplicate code.

var person = new Person();
switch (PersonEnum)
{
    case PersonEnum.Name:
        person.Name = ...
        break;
    case PersonEnum.Age: 
       person.Age = ...
       break;
     case PersonEnum.All:
       person.Name = ...         
       person.Age = ...
       break;

The example code above is a far more simplified version of what I'm dealing with, but the idea still applies.

Upvotes: 3

Views: 1196

Answers (3)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

It will be more practical to use Flags enum. In this case you can do something like this:

if (PersonEnum.HasFlag(PersonEnum.Name)) // Name is set. HasFlag is equivalent to (PersonEnum & PersonEnum.Name) != 0
{
    person.Name = ...
}

if (PersonEnum.HasFlag(PersonEnum.Age)) // Age is set
{
    person.Age = ...
}
...

In this case you don't even need to check PersonEnum.All

Your enum should be something like this:

[Flags]
enum PersonEnum 
{
  Name = 1,
  Age = 2,
  LastName = 4,
  ...
  NameAndAge = Name | Age,
  All = Name | Age | LastName ...
}

Upvotes: 6

Bronumski
Bronumski

Reputation: 14272

Actually there is a way to do this, it is not as nice as the fall through that Java supports but you can achieve something similar with goto, yep there it is. One should point out that although there is stigma associated with the goto statement perhaps this is the one place where it would be ok, preferably if the code is short, concise and easy to read.

However for this particular scenario it might not be the best choice. A better choice here would be the factory pattern.

switch (personEnum)
{
  case PersonEnum.Name:
    person.Name = "";
    goto case PersonEnum.Age;
  case PersonEnum.Age:
    ...

Upvotes: 0

ZarX
ZarX

Reputation: 1086

You could separate it into if statements instead to minimize the code a bit

if (PersonEnum == PersonEnum.All || PersonEnum == PersonEnum.Name)
   person.Name = ...
if (PersonEnum == PersonEnum.All || PersonEnum == PersonEnum.Age)
   person.Age = ...

Upvotes: 1

Related Questions