0

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;
Sarov
  • 545
  • 6
  • 17
  • May be useful: https://stackoverflow.com/questions/943398/get-int-value-from-enum-in-c-sharp – Jaskier Jan 07 '19 at 20:48
  • Enums can have different types other than `int` (though they usually don't). So the warning is technically valid. – Rufus L Jan 07 '19 at 20:54
  • Could you please have your sample be as close to the original code as possible? You cannot cast the actual `Enum` type to an int. You'll need to test `param.Value` against the actual enum definition it represents. – Ruud Kobes Jan 07 '19 at 21:05
  • @RuudKobes I changed it to be a complete program. – Sarov Jan 08 '19 at 14:58
  • @Servy Disagree with the close vote. The issue in this case is related with the fact that enums store a variable underlying type, which has nothing to do with the linked Question. – Sarov Jan 08 '19 at 15:29
  • @Sarov The answer *that you accepted* is just repeating what's in the duplicate. If you think that that's not the answer, why didn't you downvote it instead of accepting it. – Servy Jan 08 '19 at 16:17
  • @Servy Maybe I didn't understand the linked Question, but I didn't think it had anything to do with unboxing something with an *underlying* int type. – Sarov Jan 08 '19 at 17:44

3 Answers3

1

A boxed enum is only convertible to its underlying type. This will fail:

enum LongEnum: long
{
    Woops
}

object o = LongEnum.Woops;
var i = (int)o;

This is due to a more general rule: any boxed value type can only be unboxed to its type:

object o = 1; //boxed int
var s = (short)o; //fails
InBetween
  • 32,319
  • 3
  • 50
  • 90
0

Assuming you're working with C#7 you can assign the outcome of the pattern matching to a variable.

If you have an enumeration like:

public enum TestEnum
{
    A = 1,
    B = 2,
    C = 3
}

Then you can handle it using

if (param.Value is TestEnum enumValue)
{
    parameter.Value = (int)enumValue;
}

You cannot cast System.Enum to an int though, so if your sample is reflecting your actual code it won't actually compile.

Ruud Kobes
  • 185
  • 1
  • 7
-1

You can try below code mentioned in answer given at C# Iterating through an enum? (Indexing a System.Array)

The main intention here is to know that every enum value will have two parts - a name and value. Value can be converted to the integers.

Enum.GetValues return array of all values in that enum. If you want this only then only first line of code is required.

    public enum MyEnum
    {
        First,
        Second,
        Third
    }

    private void EnumValues()
    {

        Array values = Enum.GetValues(typeof(MyEnum));

        foreach (MyEnum val in values)
        {
            //// To print name and value in enum
            Console.WriteLine(String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));


            //// To get only value
            int i = (int)val;
        }
    }

Hope this helps.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37