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:
How can i correct this? or provide me a efficient code please..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With