Some facts about C#  Enum Data type

Some facts about C# Enum Data type

As we know In dot net enums are used to hold named value constants.

We can define the enum

enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

By default, it enumerator starts from a 0 value and each successive will increase by 1

means Sat=0, sun=1,Mon=2 and so on….

We can also provide the constant value explicitly shown the below example.

Ex. enum Days {Sat=1, Sun=2, Mon, Tue, Wed, Thu, Fri};

We can override the default also as we did in the above example.

Default of sat is 0 which is overridden by 1 and sun=2 so the next successor will be increased by 1, therefore, Mon=3, Tue=4, and so on...

Strange behavior of enum initialization.

We can assign the same constant value to the enum and it will comfortably accept it without giving a compilation error.

Example.

enum Days {Sat=2, Sun=2, Mon, Tue, Wed, Thu, Fri};

So both sat and Sun contains 2 value and from Mon will increase by one as said before so Mon=3, Tue=4 and so on

C# compiler doesn’t mind giving the same value which already possesses by some other constant in the Enum.

In fact, it also gives the same value to the successor name constant.

Example.

enum Days { Sat = 10, Sun = 5, Mon, Tue, Wed, Thu, Fri };

In the above example sat contains 10 which we have explicitly assigned and sun contains 5 so the next successor mon=6 … Fri=10. Ops strange.

How how can the compiler just blindly give the same value that which already possessed by another name constant.

So I think that is the open question for you all Why does this is happening?

Apart from this underlying data type for the enum is Int32 but we can change it to another integral numeric type.

We can define the different datatype by specifying the colon

Example.

enum Days : short { Sat = 10, Sun = 5, Mon, Tue, Wed, Thu, Fri };

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

But it's not recommended to use a different type other than Int32.

In the Dot net framework design guideline there is rule CA1028: Enum storage should be Int32.. According to this rule it is not recommended to change the underlying data type

I hope you learn something new :) Thanks for reading Keep learning