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;
}
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.
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.
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