0

Let's have the below class

public void HandleMessage(object message)
    {
        switch (message)
        {
            case string bookTitle:
                Console.WriteLine($"Received book with title : {bookTitle}");
                break;

            case int bookId:
                Console.WriteLine($"Received book with Id : {bookId}");
                break;

            //case (long Id,string Title) book:
            //    Console.WriteLine($"Received book Id : {movie.}");
            //    break;

            case ValueTuple<long, string> book:
                Console.WriteLine($"Received book Id : {book.Item1}, {book.Item2}");
                break;

            default:
                Console.WriteLine($"Received unknown book : {message}");
                break;
        }
    }

I'm trying to call HandleMessage method with Named Tuple as below

        var bookStore = new BookStore();
        bookStore.HandleMessage("Adam & Maro");
        bookStore.HandleMessage(9865);

        var book = (Id: 13265, Title: "ToThe.Sapce");
        bookStore.HandleMessage(book);

Is there any way to allow Named Tuple in switch statement instead of using ValueTuple ?

something like commented code

Amr Badawy
  • 7,453
  • 12
  • 49
  • 84
  • Once the tuple has been boxed up as an object, its identity as a named tuple is lost, as that's just syntactic sugar. Edit: You could always create a wrapper object, but if you're going to do that, you should just use a data class. – willaien Mar 12 '18 at 21:44
  • @willaien the issue is that switch case doesn't accept named tuple as an option like string , int – Amr Badawy Mar 12 '18 at 21:47
  • That's because the named tuple isn't a distinct type. I suggest you create a simple data class to handle this. – willaien Mar 13 '18 at 13:47

0 Answers0