Switch in C#
C# allows the use of switch
statements similar to the example provided. Here is how you can write it idiomatically in C#:
Here’s a basic switch
.
using System;
class Program
{
static void Main()
{
int i = 2;
Console.Write("Write {0} as ", i);
switch (i)
{
case 1:
Console.WriteLine("one");
break;
case 2:
Console.WriteLine("two");
break;
case 3:
Console.WriteLine("three");
break;
}
You can use commas to separate multiple expressions in the same case
statement. We use the optional default
case in this example as well.
switch (DateTime.Now.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("It's the weekend");
break;
default:
Console.WriteLine("It's a weekday");
break;
}
switch
without an expression is an alternate way to express if/else logic. Here we also show how the case
expressions can be non-constants.
DateTime t = DateTime.Now;
switch (true)
{
case var _ when t.Hour < 12:
Console.WriteLine("It's before noon");
break;
default:
Console.WriteLine("It's after noon");
break;
}
}
A type switch
compares types instead of values. You can use this to discover the type of an object. In this example, the variable t
will have the type corresponding to its clause.
void WhatAmI(object i)
{
switch (i)
{
case bool _:
Console.WriteLine("I'm a bool");
break;
case int _:
Console.WriteLine("I'm an int");
break;
default:
Console.WriteLine("Don't know type {0}", i.GetType());
break;
}
}
WhatAmI(true);
WhatAmI(1);
WhatAmI("hey");
}
}
When you run this C# code, it will produce the following output:
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type System.String
Next example: Arrays.