3

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'

Community
  • 1
  • 1
Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102

1 Answers1

10

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}",
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • thanks a lot for your reply. I have one question for you, why did you add underline `_` before `= >` I've looked at documentation and I didn't saw it's used like that. And it even wont work without that line. And that line where u'r accessing `.UserName` from unfe looks cool, to be able to do that I should previously somehow store `UserName` to that variable or? That parts looks interesting could you wrote a litle bit more about that. Thank a lot man! Appreaciate that! – Roxy'Pro Jan 21 '20 at 12:31
  • 1
    @Roxy'Pro as I said in the edit: `_` is a discard; the general pattern for a type test like this is `{DetectType} {localName}` - just: C# accepts `_` as a special case of "meh, don't care" in a range of scenarios, i.e. "I'm not going to try and access it, you do whatever you need". Compare and contrast this to the last line in the edit, where I declare a new local name for the typed value, and then access a value from that. – Marc Gravell Jan 21 '20 at 12:34
  • thank for reply! How could I add value for example username to that typed value so I might access it from UserNotFoundException. That looks awesome – Roxy'Pro Jan 21 '20 at 12:37
  • 1
    @Roxy'Pro like `public class UserNotFoundException : Exception { public string UserName { get; } public UserNotFoundException(string userName) : base("You shall not pass!") => UserName = userName; }` ? (sorry for dense formatting; comments don't allow for cleaner) – Marc Gravell Jan 21 '20 at 12:42