157 recommendations for writing high-quality code to improve C # programs--Recommendation 7: Use 0 values as default values for enumerations

Source: Internet
Author: User

Recommendation 7: Use the 0 value as the default value for the enumeration

The enumeration types allowed are byte, sbyte, short, ushort, int, uint, long, and ulong. You should always use a value of 0 as the default value for the enumeration type. However, this is not done because the default value for the enumeration type that is allowed at the time of declaration is 0 value, but it has engineering implications.

Imagine, for example, a week-week enumeration class, and we would assume that it should have 7 elements, the code looks like this:

    enum Week      {          1,          2,          3,          4,           5 ,           6 ,           7     

So, you accidentally wrote the following code, what is the output of it?

    class program      {          static  Week Week;                Static void Main (string[] args)          {              Console.WriteLine (week);          }      

Output is: 0

Week appears to have a 8th value, and unfortunately, this code does not throw an exception. Therefore, you should always specify a default value for the enumerated 0 value. In the above enumeration type week, you can explicitly remove the value of an element, and the compiler automatically counts from the 0 value, then the value of the element +1.

Note that in addition to the 8th value of week above, if the element type of the enumeration type is integer, you can also assign the values of the other integral types to week:

    Week = (week)9;      

This code does not go wrong, output: 9.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 7: Use 0 values as default values for enumerations

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.