Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch case with Boolean

Tags:

c#

I am trying to create a prefix text value for a project. I am using switch case for that. When the user select the relevant radio button we should give the prefix value.

what should I give after the "switch ()"

The value coming from user selection is a boolean value. The output is string.

any help..

 public string officePostfix()
  {
   string postfix = null;
     switch (...)
        {
            case SheetMgrForm.Goldcoast = true:
                postfix = "QLD";
                break;
            case SheetMgrForm.Melbourne = true:
                postfix = "MEL";
                break;
            case SheetMgrForm.Sydney = true:
                postfix = "SYD";
                break;
            case SheetMgrForm.Brisbane = true:
                postfix = "BIS";
                break;
        }
        return postfix;
     }
like image 355
user1445894 Avatar asked Dec 12 '22 15:12

user1445894


2 Answers

That's not how switch works. You can't put an arbitrary boolean expression in each case (assuming you mean == and not =, btw).

You need to use a set of if-else blocks, like:

if (SheetMgrForm.Goldcoast) {
    postfix = "QLD";
} else if (SheetMgrForm.Melbourne) {
    postfix = "MEL";
} else if ......

However, it looks like your design could use some rework. Having all those separate booleans is clumsy.

like image 120
Blorgbeard Avatar answered Dec 28 '22 20:12

Blorgbeard


Another approach is to use an enumeration to define your areas, then map these to a resource file. This makes it more maintainable, e.g. localization or further extension in the future, and could be useful if the list is long, i.e. automate the creation of the enum and resources via T4, or you have to query a web service, or whatever...

For example, say you have an AreaPostfixes resource file and an Area enumeration.

public enum Area
{
     Goldcoast,
     Melbourne,
     // ...
}

public static class AreaExtensions
{  
    public static string Postfix(this Area area)
    {
        return AreaPostfixes.ResourceManager.GetString(area.ToString());
    }
}

// AreaPostfixes.resx
Name       Value
Goldcoast  QLD
Melbourne  MEL

// Usage
public string GetPostfix(Area area)
{
    return area.Postfix();
}

That removes any need for switches, etc., the only thing you need to ensure is that there is a 1:1 mapping for each enum and resource. I do this via unit tests but it's easy enough to place an Assert or throw an exception if GetString returns null in the Postfix extension method.

like image 40
si618 Avatar answered Dec 28 '22 19:12

si618