case and switch c# code example
Example 1: c# switct case
using System;
public class Example
{
public static void Main()
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}
}
}
Example 2: switch c#
switch(expression)
{
case x:
break;
case y:
break;
default:
break;
}
Example 3: c# switch
using System;
public class Example
{
public static void Main()
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}
}
}
Example 4: new in c# switch expression
public static T ExhaustiveExample<T>(IEnumerable<T> sequence) =>
sequence switch
{
System.Array { Length : 0} => default(T),
System.Array { Length : 1} array => (T)array.GetValue(0),
System.Array { Length : 2} array => (T)array.GetValue(1),
System.Array array => (T)array.GetValue(2),
IEnumerable<T> list
when !list.Any() => default(T),
IEnumerable<T> list
when list.Count() < 3 => list.Last(),
IList<T> list => list[2],
null => throw new ArgumentNullException(nameof(sequence)),
_ => sequence.Skip(2).First(),
};
Example 5: C# Switch
int var = 3;
switch (var)
{
case 1:
Console.WriteLine("Ahoy!");
break;
case 2:
Console.WriteLine("Hi!");
break;
case 3:
Console.WriteLine("HELLO!");
break;
}