Precautions for enumeration Enum in C #

Source: Internet
Author: User

Some time ago, the project compilation was normal because two different items in the same enumeration were accidentally written as the same value in the project. As follows:

Enum MyEnum
{
A = 1,
B = 1
}
With curiosity, I wrote code for verification:

Enum MyEnum
{
A,
B = 2,
C,
D = 2,
E,
F = 1,
G
}
I found that:

First:

Int a = (int) MyEnum. A; // a = 0
Int c = (int) MyEnum. C; // c = 3
Int e = (int) MyEnum. E; // e = 3
Int g = (int) MyEnum. G; // g = 2
(1) If no value is specified for the first item, the default value is 0.

(2) The value of an item is not necessarily unique in enumeration.

(2) If no value is specified, the value of the following item is "always" (for no reason, if a value already exists) equal to the value of the preceding item plus 1.

(3) Enumeration items are not necessarily sorted in ascending order.
 

Second point:

Bool result1 = (MyEnum. C = MyEnum. E); // true
Bool result2 = (MyEnum. B = MyEnum. G); // true
MyEnum myE = (MyEnum) 2; // MyEnum. B
(1) enumeration is a value type. During calculation, "value" is used for calculation.

(2) When the value is converted to enumeration, search from front to back.

 

I am sorry for writing too much. Please give me some comments and give me some advice.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.