I have the following code snippet:
internal static class Program
{
private enum MyEnum
{
MyVal = 2,
}
private enum AlsoMyEnum
{
AlsoMyVal = 2,
}
private static class Thing
{
public static object DoThing(object objectIn) =>
objectIn is Enum ? (int)objectIn : objectIn;
}
[STAThread]
private static void Main(string[] args)
{
var objectOut = Thing.DoThing(MyEnum.MyVal);
var objectOut2 = Thing.DoThing(AlsoMyEnum.AlsoMyVal);
var @false = MyEnum.MyVal.GetType() == AlsoMyEnum.AlsoMyVal.GetType();
var @true = objectOut.GetType() == objectOut2.GetType();
}
}
ReSharper is complaining that "(int)objectIn" is a "Possible 'System.InvalidCastException'".
As per my understanding, this code is fine (and, thus, I should suppress the warning) - if something is an Enum, then it should be valid to cast it to an int. However, I wanted to check - am I missing something?
Is the warning correct? Or is there some other way to write this that would avoid the warning while still putting an int into parameter.Value?
EDIT
Thanks to @InBetween for pointing out that the warning is actually correct. In order to fix the code, this should be used instead:
public static object DoThing(object objectIn) => objectIn is Enum
? Convert.ChangeType(objectIn, Enum.GetUnderlyingType(objectIn.GetType()))
: objectIn;