Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumeration in C#

I am trying to enumerate the runtime input to print values of enum variable in c#. For example,

class Program
{
   enum Alphabets { a = 1, b, c, d, e, f, g, h }

   public static void Main(String[] args)
   {
       string s = Console.ReadLine();

       foreach(char c in s)
       {
           foreach(int i in Enum.GetValues(typeof(Alphabets)))
              Console.WriteLine(s[i]);
       }

       Console.ReadKey();
   }
}

I stored the user input in String s. I need to display the integer values of the string provided by the user. The above code show some error like the following: Index error! How can i correct this? or provide me a efficient code please..

like image 370
janani Avatar asked Mar 07 '26 22:03

janani


1 Answers

I think you want something along these lines:

string line = Console.ReadLine();
foreach (char c in line)
{
    string name = c.ToString();
    Alphabets parsed = (Alphabets) Enum.Parse(typeof(Alphabets), name);
    Console.WriteLine((int) parsed);
}

So this converts each character into a string, and tries to parse it as a member of Alphabets. Each parsed value is then converted into an int just by casting.

like image 58
Jon Skeet Avatar answered Mar 10 '26 12:03

Jon Skeet