Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert enum to char

Tags:

arrays

c#

enums

So I have an enum like this:

enum element
{
    Side = '|', Top = '-', Corner = '.'
}

And then I have a two-dimensional char array which only contains the chars | - .

But when I try to write:

array[2, 3] = element.Side; 

I get an error saying that "cannot implicitly convert type element to 'char'"

So... What do I do wrong? Is there an elegant way for me to turn my two-dimensional char array into an array containing the corresponding enums? I hope you understand my question.

like image 872
Niklas Avatar asked Mar 09 '26 05:03

Niklas


2 Answers

You have to cast the element.Side to a char:

arr[2, 3] = (char)element.Side

Why you should do this?

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type, as shown in the following example.

So what is happening by declaring your enum?

Under the cover, the compiler produces for each character of your enum it's correspoding integral representation. You could verify this, by creating a console application and trying to write to the console the following:

(int)element.Side

You will get 124. Please check here to verify that 124 is the decimal representation of vertical bar.

Furthermore, you could verify this by using a dissasembler. The picture below has been taken using IL DASM.

enter image description here

If you click at the Side: public static literal... a new window would be opened with the following statement.

enter image description here

What is 0x0000007C?

The Hexadecimal representation of vertical bar ! You could find further info on this here.

You could find further info regarding enum here and here.

like image 66
Christos Avatar answered Mar 11 '26 20:03

Christos


You cannot have char as your base type of an enum, therefore, it is not possible to implicitly convert an element to a char. Although you have given char values to the elements in your enum, they are converted to their int values. You have to cast before you use them:

arr[2, 3] = (char)element.Side

So actually, your code is:

enum element : int
{
    Side = '|', Top = '-', Corner = '.'
}

And if you try to set your base type to a char, the compiler will complain.

like image 32
Fatih BAKIR Avatar answered Mar 11 '26 18:03

Fatih BAKIR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!