Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use C# 8.0 switch case

I've tried to implemented c# 8.0 switch-case but it's not working unfortunatelly, I want to if case is satisfied to return a specific string for that satisfied case in switch expression.

Here's my code:

public static void GetErrMsg(Exception ex) =>
   ex switch
   {
       ex is UserNotFoundException => "User is not found.",
       ex is NotAuthorizedException => "You'r not authorized."
   };

But I gt a following message:

Error CS0201 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.

Error CS0029 Cannot implicitly convert type 'bool' to 'System.Exception'

like image 594
Roxy'Pro Avatar asked Jan 25 '26 05:01

Roxy'Pro


1 Answers

Perhaps something like:

    public static string GetErrMsg(Exception ex) =>
       ex switch
       {
           UserNotFoundException _ => "User is not found.",
           NotAuthorizedException _ => "You'r[e] not authorized.",
           _ => ex.Message, // or something; "Unknown error" perhaps
       };

The _ here is a discard; if you actually wanted to use something else from the detected type, you can name it, for example:

UserNotFoundException unfe => $"User is not found: {unfe.UserName}",
like image 92
Marc Gravell Avatar answered Jan 27 '26 17:01

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!