C #: Enum and overriding tostring on it

Source: Internet
Author: User

This article from: http://blogs.msdn.com/abhinaba/archive/2005/10/20/483000.aspx

 

I saw two posts on enums today on Eric lipperts and Chris rathjen's blog. enums are significantly different from the other types and people run into unusal problems while working with them.

C ++

The CLI Enum is considerably different fromNativeC ++ Enum and therefore you need to be careful how you define and use them in managed C ++. in new syntax (C ++/CLI Whidbey) the following Code compiles even though both the enums define the same name Cool.

enum

class Coolness // class indicates this is a C++/CLI enum

{

NotSoCool,

Cool,

SuperCool

};

enum

class TempRange

{

Cool,

Hot,

VeryHot,

};

In old syntax (pre Whidbey) You need to define the enum_ ValueEnum coolness. in case you drop the class then you are using the native C ++ Enum and according to C ++ specification the enumerator declarations are promoted to the same scope as the enumerated type declaration and the code will fail to compile pointing out a redefinition of cool.

C #

In C # We do need not care about these as there is only one definition of Enum which is that of the CLI enum.

Common things like the first Enum member get the value 0, the value of a subsequent member is calculated by adding 1 to the member textually preceeding it, you can assign values explicitely to a Enum member are well-known. however there are some not so well known usages as well.

enum Coolness : byte

{

NotSoCool = 5,

Cool,

VeryCool = NotSoCool + 7,

SuperCool

}

Coolness

coolType = Coolness.VeryCool;

Console

.WriteLine("Underlying type: {0}", Enum.GetUnderlyingType(coolType.GetType()));

Console.WriteLine("Type Code : {0}", coolType.GetTypeCode());

Console.WriteLine("Value : {0}", (byte)coolType);

By default the compiler uses int32 to store the enum members. here we are asking it to use byte. verycool uses a reference to the notsocool and will get the value 12. so the out put of the code will be

Underlying type: system. byte
Type Code: byte
Value: 12

Since all enums have system. Enum as the abstract base type, a lot of funcionality becomes available to get details about the enum type.

If you want to print the value of the enum then it can be done in the following ways

Console

.WriteLine(coolType.ToString("G")); // name of the constant

Console.WriteLine(coolType.ToString("F")); // name of the constant

Console.WriteLine(coolType.ToString("X")); // value is hex

Console.WriteLine(coolType.ToString("D")); // value in decimalOutput:
VeryCoolVeryCool0C12

F and G gives the same value in this case. They differ based on whether flagsattriied is applied to it.

You can also get a array filled with either the value (getvalues) or names (getnames) of all the constants in The enum.

string

[] names = Enum.GetNames(typeof(Coolness));

int index = 0;

foreach (Coolness coolVal in Enum.GetValues(typeof(Coolness)))

{

Console.WriteLine("{0,-10} => {1}", names[index++],

coolVal.ToString(

"D"));

}

This prints

Notsocool => 5
Cool => 6
Verycool => 12
Supercool => 13

You can also query the name of the constant in the enum that has the specified value or whether a value is defined in the enum or not. The following will print cool and 5 is not defined.

Console

.WriteLine(Enum.GetName(typeof(Coolness), 6));

if(!Enum.IsDefined(typeof(Coolness), (byte)7))

Console.WriteLine("5 is Not Defined");

Overriding tostring ()

You cannot override the tostring Of The enum type. so in case you wanted to display "not so cool" instead of notsocool when someone called tostring on your Enum type then you cannot do that simply by overriding the tostring.

This is a common issue that comes up frequently when you want to show values in reports, web pages, XML where you want to put in human readable text for enum values. commonly people use non-generic solution of maintaining arrays of these descriptions and get text out of them by indexing using the enum value or some other things like storing it in a hashtable and using the tostring Value as the key to get the desciption out.

A generic solution wocould be to apply custom attributes on the enum constants and write static methods to get the desciption. See the modified Code below

using

System;

using

System.Reflection;

namespace

FunWithEnum

{

enum Coolness : byte

{

[

Description("Not so cool")]

NotSoCool = 5,

Cool,

// since description same as ToString no attr are used

[

Description("Very cool")]

VeryCool = NotSoCool + 7,

[

Description("Super cool")]

SuperCool

}

class Description : Attribute

{

public string Text;

public Description(string text)

{

Text = text;

}

}

class Program

{

static string GetDescription(Enum en)

{

Type type = en.GetType();

MemberInfo[] memInfo = type.GetMember(en.ToString());

if (memInfo != null && memInfo.Length > 0)

{

object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description),
false
);

if (attrs != null && attrs.Length > 0)

return ((Description)attrs[0]).Text;

}

return en.ToString();

}

static void Main(string[] args)

{

Coolness coolType1 = Coolness.Cool;

Coolness coolType2 = Coolness.NotSoCool;

Console.WriteLine(GetDescription(coolType1));

Console.WriteLine(GetDescription(coolType2));

}

}

}

Using this approach is pretty generic because for all Enum constants that have this attribute applied to it, the desciption will be picked up from it and for those that do not have the attribute the common tostring () method will be called to get the description. however, the getdescription uses reflection and can be slow.

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.