Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

![enter code here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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,
}

>Solution :

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;
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading