I use C# version 7.3 and I want to use double result = operation switch in this version, and my code throws an error – what I do?
The error is thrown on switch statement.
Can anyone help me? I’ll be very thankful…
// Function for handling the arithmetic operations.
void PerformArithmetic(string operation)
{
double num1, num2;
Console.Write("Enter the first number: ");
while (!double.TryParse(Console.ReadLine(), out num1))
{
Console.Write("Invalid input. Please enter a valid number: ");
}
Console.Write("Enter the second number: ");
while (!double.TryParse(Console.ReadLine(), out num2))
{
Console.Write("Invalid input. Please enter a valid number: ");
}
double result = operation switch
{
"Addition" => num1 + num2,
"Subtraction" => num1 - num2,
"Multiplication" => num1 * num2,
"Division" => num2 != 0 ? num1 / num2 : double.NaN,
=> throw new InvalidOperationException("Unknown operation")
};
if (operation == "Division" && num2 == 0)
{
Console.WriteLine("Error: Division by zero is not allowed.");
}
else
{
Console.WriteLine($"Result of{operation}: {result}");
}
Console.WriteLine("Press any key to return to the calculation menu.");
Console.ReadLine();
}
MANSOOR KHOSHAL is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6
Switch expressions don’t exist until C# 8, so: either update your compiler version (which is quite significantly out-of-date – from May 2018) or use a different syntax. For example, a switch statement:
double result;
switch (operation)
{
case "Addition":
result = num1 + num2;
break;
// ... etc
default:
throw new InvalidOperationException("Unknown operation");
}