Enum inheriting from int

10,765

Solution 1

According to the documentation:

Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int.

So, no, you don't need to use int. It would work with any integral type. If you don't specify any it would use int as default and it's this type that will be used to store the enumeration into memory.

Solution 2

Enums are implicitly backed by integers.
: int just restates the default, just like void M(); vs. private void M();.

You can also create enums that are backed by other intergral types, such as enum GiantEnum : long.

Solution 3

You don't need to, it's implied. According to MSDN:

An enumeration is a set of named constants whose underlying type is any integral type except Char. If no underlying type is explicitly declared, Int32 is used. Enum is the base class for all enumerations in the .NET Framework.

This means you could usebyte, sbyte, ushort, int, uint, long, or ulong.

Also, setting the values the way you have described (blah=0, blahblah=1), while redundant, is OK, since, according to the C# Specification

If the declaration of the enum member has no initializer, its associated value is set implicitly, as follows:

• If the enum member is the first enum member declared in the enum type, its associated value is zero.

• Otherwise, the associated value of the enum member is obtained by increasing the associated value of the textually preceding enum member by one. This increased value must be within the range of values that can be represented by the underlying type, otherwise a compile-time error occurs.

Solution 4

int is by default the type of any enum. It does not need to be declared explicitly.

It's more useful when you want to use something else (byte, long, and friends).

Solution 5

You don't need to inherit from int but by default it does. You can inherit from other integral types (byte, long, etc) if you want to. An example would be if you wanted to save memory or column space in a DB.

Share:
10,765
slandau
Author by

slandau

Updated on June 07, 2022

Comments

  • slandau
    slandau about 2 years

    I've found this all over the place in this code:

    public enum Blah: int
    {
        blah = 0,
        blahblah = 1
    }
    

    Why would it need to inherit from int? Does it ever need to?