1

I have this code and I am wondering. Could this be changed to use the new C# expression as a way to eliminate the need for the break;

switch (reposition)
{
    case (int)POS.First: cIndex = 0; break;
    case (int)POS.Last: cIndex = cIndexLast; break;
    case (int)POS.Prev: cIndex--; break;
    case (int)POS.Next: cIndex++; break;
}
reposition = null;

Response for Hogan

enter image description here

Alan2
  • 23,493
  • 79
  • 256
  • 450

1 Answers1

6

The only issue is you can't use -- and ++

cIndex = (POS)resposition switch
{
   POS.First =>  0,
   POS.Last  => cIndexLast,
   POS.Prev  => cIndex-1,
   POS.Next  => cIndex+1
};

re comments about not covered - here we are casting to a POS so all cases in POS are covered. You should have code before this to check and see that the numeric values of reposition are in the range of pos. (or if you code does this naturally you don't have to worry.)

You can use

if (POS.IsDefined(typeof(POS), resposition) { ... }

hat tip https://stackoverflow.com/a/29489/215752

Hogan
  • 69,564
  • 10
  • 76
  • 117
  • Thanks very much – Alan2 Dec 11 '19 at 01:10
  • It's giving me a message saying the switch expression doesn't handle all possible inputs. Do you have a suggestion on how I could fix this? thanks – Alan2 Dec 11 '19 at 01:15
  • 1
    What is POS? You seem to no cover every possible enumerator in it. If you do not want to cover anything else, use underscore to act as default: `_ => throw new NotSupportedException()` – Knight0fDragon Dec 11 '19 at 01:29
  • public enum POS { First = 0, Prev = 1, Next = 2, Last = 3 } – Alan2 Dec 11 '19 at 01:32
  • I believe the casting to int is not needed, maybe that is throwing you off. – Knight0fDragon Dec 11 '19 at 01:35
  • I removed the int but then it gives an error saying a cast is needed. – Alan2 Dec 11 '19 at 02:38
  • @Alan2 did you cast to POS in the top like I did in my code sample? – Hogan Dec 11 '19 at 14:01
  • @Hogan - I tried the change you suggested but this time get a different message. I added a screen print to the answer. – Alan2 Dec 12 '19 at 03:23
  • I fixed the typo but still gives the same error. Only solution I have other than ignoring is to add this: _ => throw new InvalidEnumArgumentException("Unhandled value: " + reposition.ToString()) This seems to stop the warning from appearing – Alan2 Dec 12 '19 at 08:14