Thread: convert type using string with switch error

  1. #1
    Registered User
    Join Date
    Mar 2019
    Posts
    5

    convert type using string with switch error

    trying to allow user input to determine a case selection. Obv some error with string conversion.

    Code:
    using System;
    
    public enum Color { Red, Green, Blue }
    
    public class Example
    {
       public static void Main()
       {
                  Console.WriteLine("Type in a string");
                string input;
                input = Console.ReadLine();
          switch (input)
          {
             case Color.Red:
                Console.WriteLine("red");
                break;
             case Color.Green:
                Console.WriteLine("blue");
                break;
             case Color.Blue:
                Console.WriteLine("green");   
                break;
             default:
                Console.WriteLine("The color is unknown.");
                break;   
          }
          Console.ReadKey(true);
       }
    }

  2. #2
    Registered User cstryx's Avatar
    Join Date
    Jan 2013
    Location
    Canada
    Posts
    123
    There's no implicit conversion here for things like this. How are you expecting a string to be translated to the enum type? You need to parse the input to the enum type if you want this to work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to Convert a Hash Digest Type Int to a String
    By xintvl in forum C Programming
    Replies: 2
    Last Post: 11-01-2017, 12:50 PM
  2. Replies: 3
    Last Post: 04-29-2008, 01:42 PM
  3. Convert String to enum type
    By c9dw2rm8 in forum C Programming
    Replies: 1
    Last Post: 02-23-2008, 07:00 PM
  4. How to convert type string to char/double ?
    By Hermitsky in forum C++ Programming
    Replies: 6
    Last Post: 07-08-2004, 03:25 PM
  5. Convert type string to a number
    By ejholmes in forum C# Programming
    Replies: 2
    Last Post: 04-21-2004, 01:33 AM

Tags for this Thread