Problem with Switch Expression in C#

Shervan360 1,601 Reputation points
2022-10-23T14:44:58.193+00:00

Could you please tell me How I can solve the problem?

Error CS0029 Cannot implicitly convert type 'bool' to 'ConsoleApp3.MyCustomer'

class MyCustomer : IComparable<MyCustomer>  
{  
    public int ID { get; set; }  
    public string FirstName { get; set; }  
    public string LastName { get; set; }  

    public int CompareTo(MyCustomer? other) => other switch  
    {  
        ID > other.ID => 1,  
        ID < other.ID => -1,  
        _ => 0  
    };  
}  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,002 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,436 Reputation points
    2022-10-23T19:27:56.717+00:00

    Why not go with the following

    class MyCustomer : IComparable<MyCustomer>  
    {  
        public int ID { get; set; }  
        public string FirstName { get; set; }  
        public string LastName { get; set; }  
        public int CompareTo(MyCustomer? other)   
            => ID.CompareTo(other!.ID);  
    }  
    
    1 person found this answer helpful.
    0 comments No comments

  2. Bruce (SqlWork.com) 66,226 Reputation points
    2022-10-23T16:02:29.14+00:00

    The switch expression uses pattern matching. You are not using the correct syntax for relational patterns.

    https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching

    Simple fix

         public int CompareTo(MyCustomer? other) => other switch  
         {  
             > ID => -1,   
             < ID => 1,  
             _ => 0  
         };  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.