Enumeration and casting to integer question

  • Thread starter Thread starter Mortimer Schnurd
  • Start date Start date
M

Mortimer Schnurd

Bear with me if you will, I am now learning C# after programming in VB
for several years. My question is rather simple. I am having trouble
understanding how to use an enumeration in the bracketed index of an
array variable. I am trying to relate an enum to an array of strings
and refer to an array item by the enum.

enum MyEnum { Key1, Key2, Key3, Key4, Key5 } ;
string[] Mystring = {"key1", "key2", "key3", "key4", "key5" };
..
..
..
string val = Mystring[Myenum.Key2];

The last statement gets a compiler error "cannot implicitly
convert...".

Ok, I understand the implicit conversion problem but how do I cast the
bracketed variable to an int within the brackets? The compiler
complains if I try something like
string val = Mystring[(int)Myenum.Key2];

Thanks for any help.
 
Hi Mortimer,
string val = Mystring[(int)Myenum.Key2];

No, it doesn't complain about the type casting. This is the right way to do
it. It complains because you have misspelled the name of the enum type.
string val = Mystring[(int)MyEnum.Key2];
Pay attention on the capital E in MyEnum. Don't forget unlike VB C# is case
sensitive.
 
Back
Top