1

In the following code-snippet, can the inside of the if ever be reached, if yes, under which circumstances?

MyEnum foo = ...;

if(!Enum.IsDefined(typeof(MyEnum), foo))
{
    // reachable?
}

I have a WebController which expects a MyEnum as Parameter. This parameter is then given to a Service, with the given check. Now I wonder how that check could ever be false, given that foo needs to be a value from MyEnum or an ArgumentException at an earlier point (e.g. if the user provided an illegal argument).

The code definitely uses a variable of type MyEnum, not a string or int.

JFBM
  • 944
  • 1
  • 11
  • 24
  • Read the [documentation for Enum.IsDefined()](https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?view=net-5.0). It says: *"Returns a Boolean telling whether a given integral value, or its name as a string, exists in a specified enumeration."* – Robert Harvey Mar 26 '21 at 16:28

1 Answers1

1

Yes, it's reachable. For example:

public enum MyEnum { Foo = 1 }

// ...

MyEnum foo = (MyEnum)9999;

if (!Enum.IsDefined(typeof(MyEnum), foo))
{
    Console.Write("reachable");
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Why can you do this? (Question obviously not directed at you.) I have only ever assigned Enum-Values to my variables, not casted integers. So much for that. Thank you. – JFBM Mar 26 '21 at 16:35
  • @JFBM: Its common that you cast integers to an enum type. If that integer comes from an external system it would be a good idea to use `Enum.IsDefined` first. It's always possible that someone changes those integers which might break such casts without a compiler error. – Tim Schmelter Mar 26 '21 at 16:38