Prerequisites :
Net Core version 3 and Visual Studio 2019 Community Edition is installed on your machine.
In the Exercise we have create .Net Core console application.
Make Sure under Dependencies you add this before running the application as it won’t compile
<LangVersion>8.0</LangVersion>
Below is the sample for switch and switch expression c#8.
Full Source Code Here :-https://github.com/japnam89/dotnetcoresamples/tree/master/SwitchExample-JS
//Example 1 with old switch c#5 etc
var caseSwitch = 1;
var result="";
switch (caseSwitch)
{
case 1:
result = "Case 1";
break;
case 2:
result = "Case 2";
break;
case 3:
result = "Case 3";
break;
default:
result = "Default Case";
break;
}
Console.WriteLine(result);
2.)This is the example we should implement using c# 8 switch expression
//Now using c# 8 switch expression
var caseSwitch2 = 2;
var result2 = "";
result2 = caseSwitch2 switch
{
1 => "Case 1",
2 => "Case 2",
3 => "Case 3 ",
_ => "Default Case"
};
Console.WriteLine("Using c#8 Switch expression:\n"+ result2);
}
}
}
Output will be :