简体   繁体   中英

c# Using enum in Switch Case throwing exception

I am working on .NET 6.0 application, I have enum that I am trying to use in switch as to compare with string value but getting exception.

error

![在此处输入代码

private static bool ValidateAlphanumericCase(string text, string fieldName)
    {
        if (!string.IsNullOrWhiteSpace(fieldName))
        {
            var rule = GetRule(fieldName).TxtFieldFormat; // string value

            switch (rule)
            {
                case TextFieldFormat.AlphanumericUpperCase.ToString():
                    break;

                case TextFieldFormat.AlphanumericLowerCase.ToString():
                    break;
            }

        }
        else
        {
            new EmptyFieldNameException();
        }

        return false;
    }

enum

 public enum TextFieldFormat
{
    AlphanumericUpperCase = 0,
    AlphanumericLowerCase = 1,
}
TextFieldFormat.AlphanumericUpperCase.ToString()

This is a method invocation expression and it is not a valid pattern for swith statement.

You can find all valid patterns here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns

The closest pattern is type pattern or constant pattern, I guess the compiler recognizes AlphanumericUpperCase as a nested class of TextFieldFormat and fails.

In this case you can use nameof operator.

 switch (rule)
 {
      case nameof(TextFieldFormat.AlphanumericUpperCase):
          break;
      case nameof(TextFieldFormat.AlphanumericLowerCase):
          break;
 }

Seems you understood switch-case block a little bit different.

A switch block is simply a shortcut (but more performant shortcut) of many if - else if - else blocks. Of course they are not the same, but their working logic almost the same.

With this very little info, you can easily think about what's wrong in your code.

Bingo, you're right! Case blocks should check the state. ( Boolean value..Just interests with either the given statement results true or false ..)

After checking the boolean result, Which case 's statement match, code continues on that case block.

So, in your situation your code could be like this :

switch (rule)
{
    
/// Some statements need to put in paranthesis. Also you would need put business codes of cases into curly braces.
/// I write from my mind.
/// So please try paranthesis and/or braces if this code break.

case rule==TextFieldFormat.AlphanumericUpperCase.ToString():
DoSomethingWithFirstCase(); break;

case rule==TextFieldFormat.AlphanumericLowerCase.ToString():
DoSomethingWitSecondCase(); break;

default: DoSomethingWhenNoMatchWithOtherCases();
}

Hope this helps.

你也可以这样使用

TextFieldFormat.AlphanumericUpperCase.ToString("g" or "G")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM