Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we can't have "char" enum types

Tags:

c#

enums

char

I want to know why we can't have "char" as underlying enum type. As we have byte,sbyte,int,uint,long,ulong,short,ushort as underlying enum type. Second what is the default underlying type of an enum?

like image 641
Praveen Sharma Avatar asked Feb 21 '09 13:02

Praveen Sharma


People also ask

Can enum have char value?

First of all, YES, we can assign an Enum to something else, a char !

Do enums have types?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

Can we have string enum?

We can't define enumeration as string type. The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

Which datatype can be used with enum?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.


1 Answers

I know this is an older question, but this information would have been helpful to me:

It appears that there is no problem using char as the value type for enums in C# .NET 4.0 (possibly even 3.5, but I haven't tested this). Here's what I've done, and it completely works:

public enum PayCode {     NotPaid = 'N',     Paid = 'P' } 

Convert Enum to char:

PayCode enumPC = PayCode.NotPaid; char charPC = (char)enumPC; // charPC == 'N' 

Convert char to Enum:

char charPC = 'P'; if (Enum.IsDefined(typeof(PayCode), (int)charPC)) { // check if charPC is a valid value     PayCode enumPC = (PayCode)charPC; // enumPC == PayCode.Paid } 

Works like a charm, just as you would expect from the char type!

like image 197
kad81 Avatar answered Sep 27 '22 23:09

kad81