"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 110: Using classes instead of enums

Source: Internet
Author: User

Recommendation 110: Use classes instead of enums

An enumeration (enum) is used to represent a fixed set of values. For example, to represent the week information, we can define an enumeration week:

    enum Week    {        Monday,        Tuesday,        Wednesday,        Thursday,        Friday,        Saturday,        Sunday    }

The greatest advantage of an enumeration is that its type is a value type. Compared to reference types, it can improve performance in key algorithms because it does not need to be created in the heap. However, if this is not the case, we might as well have the class (reference type) instead of the enumeration. The code is as follows:

        classWeek { Public Static ReadOnlyWeek Monday =NewWeek (0);  Public Static ReadOnlyWeek Tuesday =NewWeek (1); //omitted            Private int_infotype; PrivateWeek (intInfoType) {_infotype=InfoType; }        }

We implement the construction method of type week to private, which effectively prevents the type from generating an instance of the class externally, making it behave closer to the enumeration.

The advantage of class week compared to enumeration week is that it can add methods or override base class methods to provide rich functionality. In the case of the week, if you want to provide a more meaningful string, such as specifying Monday is Monday, this is not natural support for enumerations. It's even going to be a big bother. Once someone has implemented this feature of enumerations:

    enumWeek {[Enumdescription ("Monday")] Monday, [Enumdescription ("Tuesday")] Tuesday} [AttributeUsage (Attributetargets.field, AllowMultiple=false)]     Public Sealed classEnumdescriptionattribute:attribute {Private stringdescription;  Public stringDescription {Get{return  This. Description;} }         PublicEnumdescriptionattribute (stringdescription):Base()        {             This. Description =description; }    }     Public Static classEnumhelper { Public Static stringgetdescription (Enum value) {if(Value = =NULL)            {                Throw NewArgumentNullException ("value"); }            stringDescription =value.            ToString (); FieldInfo FieldInfo=value. GetType ().            GetField (description); enumdescriptionattribute[] Attributes= (enumdescriptionattribute[]) fieldinfo.getcustomattributes (typeof(Enumdescriptionattribute),false); if(Attributes! =NULL&& attributes. Length >0) {Description= attributes[0].            Description; }            returndescription; }    }        Static voidMain (string[] args)        {Console.WriteLine (Enumhelper.getdescription (Week.monday)); }

Output:

Monday

If you do not add attribute Enumdescription attributes to an enumeration element, we can only use:

Console.WriteLine (Enumhelper.getdescription (Week.monday));

Output:

Monday

If you are in a class, there is no such inconvenience of enumerating, because you can resolve the problem by overriding the ToString method of object. The code is as follows:

        Static voidMain (string[] args)        {Console.WriteLine (week.monday); }        classWeek { Public Static ReadOnlyWeek Monday =NewWeek (0);  Public Static ReadOnlyWeek Tuesday =NewWeek (1); //omitted            Private int_infotype; PrivateWeek (intInfoType) {_infotype=InfoType; }             Public Override stringToString () {Switch(_infotype) { Case 0:                        return "Monday";  Case 1:                        return "Tuesday"; default:                        Throw NewException ("Incorrect Week info! "); }            }        }

Classes can give more types of behavior than enumerations. Of course, if the application satisfies the following features, we should consider using enumerations more:

    • Efficiency. This is because the enumeration is a value type.
    • Type is used internally, and no more behavior attributes need to be added.
    • The type element does not need to provide additional attributes.

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

Go to write high-quality Code 157 recommendations for improving C # programs--Recommendation 110: Using classes instead of enums

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.