Producing a value from some other value is a very common pattern and one that switch
is often used for. Unfortunately using switch statements directly involve declaring the variable then setting it and break
ing inside each case
is verbose and error-prone.
This can be somewhat mitigated by simply wrapping the switch statement in a method of its own so you can take full advantage of the return
keyword from each case
thus avoiding the need to declare and set the variable and do away with all break
statements.
In C# 8 this is no longer necessary as the expression form of switch
to allow values to be emitted directly without wrapping them in a new function.
Code
C#
var sysInfo = new SysInfo();
GetNativeSystemInfo(ref sysInfo);
var procArch = sysInfo.ProcessorArchitecture switch
{
0 => "x86",
6 => "IA64",
9 => "x64",
_ => string.Empty;
};
C#
var sysInfo = new SysInfo();
GetNativeSystemInfo(ref sysInfo);
var procArch = GetPlatform(sysInfo);
string GetPlatform(SystemInfo sysInfo)
{
switch (sysInfo.ProcessorArchitecture)
{
case 0: return "x86";
case 6: return "IA64";
case 9: return "x64";
default: return string.Empty;
}
}