I have to implement the following in a switch
statement:
switch(num)
{
case 4:
// some code ;
break;
case 3:
// some code ;
brea
Note: the answer below was written in 2009. Switch patterns were introduced in C# 7.
You can't - switch/case is only for individual values. If you want to specify conditions, you need an "if":
if (num < 0)
{
...
}
else
{
switch(num)
{
case 0: // Code
case 1: // Code
case 2: // Code
...
}
}
The other way around would be possible also (relating to Jon Skeet's answer):
switch(num)
{
case a:
break;
default:
if( num < 0 )
{}
break;
}
You will have to use if, wether you want or not. Switch is only capable of comparing your value to constant values.
If your num can't be less than zero:
public int GetSwitch(int num) { return num < 0 ? -1 : num; }
switch(GetSwitch(num))
{
case 4: // some code ; break;
case 3:// some code ; break;
case 0: // some code ; break;
case -1 :// some code ; break;
}
If it can, use some other "non-existent" number such as int.MinValue.
In twist of C# fate, this has come all the way back around. If you upgrade to C# 9.0, your original switch statement will now compile! C#9.0 has added Relational patterns to pattern matching in general, which includes switch statements.
You can now do some really funky stuff, like this:
var num = new Random().Next();
switch(num)
{
case < 0:
// some code ;
break;
case 0:
// some code ;
break;
case > 0 and < 10:
// some code ;
break;
case > 20 or (< 20 and 15):
// some code ;
break;
}
Note the use of literal 'and' and 'or' in the last case, to allow && and || type expressions to compile.
To use C# 9, make sure the XmlNode LangVersion is set to Latest or 9.0 in the csproj file, in a property group
e.g.
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Platforms>AnyCPU;x86</Platforms>
<Configurations>Debug;Release;Mock</Configurations>
<LangVersion>Latest</LangVersion>
</PropertyGroup>
What you could do is to use a delegate like this.
var actionSwitch = new Dictionary<Func<int, bool>, Action>
{
{ x => x < 0 , () => Log.Information("less than zero!")},
{ x => x == 1, () => Log.Information("1")},
{ x => x == 2, () => Log.Information("2")},
{ x => x == 3, () => Log.Information("3")},
{ x => x == 4, () => Log.Information("4")},
{ x => x == 5, () => Log.Information("5")},
};
int numberToCheck = 1;
//Used like this
actionSwitch.FirstOrDefault(sw => sw.Key(numberToCheck)).Value();
Just swap out what you wan´t to perform where the Log.Information("x") is and you have your "switch" statement.
You will need to some error handling if you check for a key that is "found" by the Func.
If you like to see the Func version of the switch I just wrote a blog post with Switch example chapter.
But if you can use C# 7 it will give you better switch capabilities.