Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 7 Pattern Match with a tuple

Is it possible to use tuples with pattern matching in switch statements using c# 7 like so:

switch (parameter)
{
   case ((object, object)) tObj when tObj.Item1 == "ABC":
        break;
}

I get an error that says tObj does not exist in the current context.

I have tried this as well:

switch (parameter)
{
   case (object, object) tObj when tObj.Item1 == "ABC":
        break;
}

This works fine:

switch (parameter)
{
   case MachineModel model when model.Id == "123":
        break;
}
like image 369
jharr100 Avatar asked Jun 22 '17 18:06

jharr100


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in coding language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

Remember that C#7 tuples are just syntactic sugar, so (object, object) is really just System.ValueTuple<object, object>.

I guess that the dev team didn't take this particular situation into account for the new syntax for tuples, but you can do this:

switch (parameter)
{
    case System.ValueTuple<object, object> tObj when tObj.Item1 == "x":
        break;
}

Also, since the "var pattern" will match anything and respect the type, the above can be simplified to:

switch (parameter)
{
    case var tObj when tObj.Item1 == "x":
        break;
}
like image 192
DavidG Avatar answered Oct 01 '22 19:10

DavidG