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'
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}",
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With