Brave Soul
Brave Soul

Reputation: 3620

Switch case on Enum values

The feature recursive patterns is currently in preview, to use preview feature, please select preview version

switch (transactionRecieved)
{
   case TransactionType.TransactionName.ToString():
   break;
   case TransactionType.TransactionName1.ToString():
   break;
}

I am not using anything new. This is the general scenario and we use it all time like this for enum

TransactionType is a enum

I also went through this post not found it useful.SO Post

I need to use enum in swith statement and I am not able to use it. could anyone help me on that part

Upvotes: 1

Views: 1696

Answers (1)

Caius Jard
Caius Jard

Reputation: 74660

If you're asking "why doesn't this work"? I'm not sure you do use it all the time like that because case expects a constant value:

enter image description here

Parse your string transactionRecieved to a TransactionType enum with Enum.Parse or Enum.TryParse<T> and then remove the ToString() from your case, perhaps like:

    var x = "Whatever";
    if(Enum.TryParse<TransactionType>(x, out xEnum)){
      switch(xEnum){
        case TransactionType.Whatever:
          break;
      }
    }

Notes: * xEnum is in scope within the if

  • Enum.IsDefined can be used in conjunction with Enum.Parse (but I find tryparse neater)

Upvotes: 4

Related Questions