2

If I create an enum like this

public enum ImportType
{
   Direct,
   Indirect,
   InBond
}

and I have a method that takes an ImportType as parameter as follows

public bool ProcessValidImport(ImportType type)
{
    // Process ImportType variable here
}

I can go and call the method as follows

bool blnProcessed = ProcessValidImport((ImportType)7);

But the ImportType variable value of 7 passed in to the method is not valid at all because any integer will work if cast. The enum defaults to an int type, so what is the best way to validate that an enum in this case is in fact a valid ImportType.

Jon Meyers
  • 45
  • 6
  • You can [test](https://msdn.microsoft.com/en-us/library/system.enum.isdefined(v=vs.110).aspx) and throw an `ArgumentOutOfRangeException`. – Damien_The_Unbeliever Oct 27 '16 at 07:23
  • Are you looking for this ProcessValidImport(ImportType.Direct);? – Vivek Nuna Oct 27 '16 at 07:27
  • I just wouldn't use them.... They're useful for flags, like `BindingFlags.Public | BindingFlags.Instance`, but in my opinion if you use them in control flow then you will almost always not be following open closed. – Callum Linington Oct 27 '16 at 07:49
  • 1
    @CallumLinington would using validation like this below 'Enum.IsDefined' not ensure that the internal workings of the class remains unmodified? Thereby maintaining open closed principal? Sorry, I'm a newbie, so I genuinely don't know. I know that I can make the class "Open" by extending it via inheritance. – Jon Meyers Oct 27 '16 at 08:08

1 Answers1

2

I don't know if I understood you correctly but you can validate enum easily using:

int value = 7;
bool isDefined = Enum.IsDefined(typeof (ImportType), value);
Fka
  • 6,044
  • 5
  • 42
  • 60