Reputation: 131
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.
Upvotes: 2
Views: 4158
Reputation: 53958
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.
If you click at the Side: public static literal...
a new window would be opened with the following statement.
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.
Upvotes: 10
Reputation: 4715
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.
Upvotes: 2