See the samples from the doc : switch expression (C# reference)
Multi-statement swich in C#
I want to use two enumaration in one swich; Here's an example
enum testenum_1 : byte { value1 =0 , value2 = 1 }
enum testenum_2 : byte { value3 = 0, value4 = 1 }
to here everything is normal , so what i want
switch ((testenum_1,testenum_2))
{
case (testenum_1.value1,testenum_2.value3):
break;
default:
break;
}
basicly this is what i want to do in C# ( least Net Framework and latest C# Installed , don't say that ) , but i can't do it. Thanks 4 your help.
Developer technologies C#
4 answers
Sort by: Most helpful
-
-
Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
2022-06-29T17:00:02.913+00:00 C# 8 was the first version to support tuple pattern matching. the 4.8 framework only supports C# 7.3,
you will need to use if statements
-
Karen Payne MVP 35,586 Reputation points Volunteer Moderator
2022-06-30T10:01:19.167+00:00 The following was done with .NET Framework 4.8 and .NET Core 5 (currently don't have Core 6 installed). My personal choice is using if statement as I work with a team of mixed understanding of C#.
Full source in a GitHub repository.
partial class Program { #region Core public static int Selection(Item sender) => (sender.Enum1, sender.Enum2) switch { (Enum1.Value1, Enum2.Value3) => 1, (Enum1.Value2, Enum2.Value4) => 2, _ => throw new NotSupportedException() }; public static int Selection1(Item sender) { // pattern matching if (sender is { Enum1: Enum1.Value1, Enum2: Enum2.Value3 }) { return 1; } else if (sender is { Enum1: Enum1.Value2, Enum2: Enum2.Value4 }) { return 2; } else { throw new NotSupportedException(); } } public static int Selection2(Item sender) => sender switch { { Enum1: Enum1.Value1, Enum2: Enum2.Value3 } => 1, { Enum1: Enum1.Value2, Enum2: Enum2.Value4 } => 2, _ => throw new NotSupportedException() }; #endregion #region 4.8 public static int SelectionConventional(Item sender) { if (sender.Enum1 == Enum1.Value1 && sender.Enum2 == Enum2.Value3) { return 1; } else if (sender.Enum1 == Enum1.Value2 && sender.Enum2 == Enum2.Value4) { return 2; } else { throw new NotSupportedException(); } } #endregion }
-
Rijwan Ansari 766 Reputation points MVP
2022-06-30T15:30:34.42+00:00 Hi
It's supported as from .NET 4.7 and C# 8. The syntax is somehow same as you mentioned, but with some parenthesis.
Example:switch ((intVal1, strVal2, boolVal3)) { case (1, "hello", false): break; case (2, "world", false): break; case (2, "hello", false): break; }
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#tuple-patterns
Sample with return values:
string result = (intVal1, strVal2, boolVal3) switch { (1, "hello", false) => "Combination1", (2, "world", false) => "Combination2", (2, "hello", false) => "Combination3", _ => "Default" };
https://stackoverflow.com/questions/7967523/multi-variable-switch-statement-in-c-sharp