Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to cast enums to int in C#?

This is my code:

internal enum WindowsMessagesFlags {
    WM_EXITSIZEMOVE      = 0x00000232,
    WM_DISPLAYCHANGE     = 0x0000007e,
    WM_MOVING            = 0x00000216,
}

protected override void WndProc(ref Message m) {
    switch(m.Msg) {
        case (int)WindowsMessagesFlags.WM_DISPLAYCHANGE:
            FixWindowSnapping();
            break;
        case (int)WindowsMessagesFlags.WM_EXITSIZEMOVE:
            SaveWindowProperties();
            break;
        case (int)WindowsMessagesFlags.WM_MOVING:
            KeepProperLocation(ref m);
            break;
    }
}

Is there anyway to prevent the casting?

like image 271
rfgamaral Avatar asked Nov 28 '08 15:11

rfgamaral


People also ask

How do I cast enum as string?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Is enum an int?

An enum type is represented by an underlying integer type. The size of the integer type and whether it is signed is based on the range of values of the enumerated constants. In strict C89 or C99 mode, the compiler allows only enumeration constants with values that will fit in "int" or "unsigned int" (32 bits).

Do enums have to be ints?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Is an enum an int in C?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want.


1 Answers

What is Message.Msg defined as?

I'm betting it is Int32.

I'm also betting WindowsMessagesFlags is your type, but Message is from the framework.

Which means you're using your own enum with a framework-built object, and of course they are going to have some incompatibilities regarding types.

An enum is a strong type, not just a number, it is a number with a name in a context. This name, context, number, part isn't directly compatible with just numbers, and that's why you need to cast.

like image 120
Lasse V. Karlsen Avatar answered Nov 03 '22 01:11

Lasse V. Karlsen