August 2010 Entries

If you are working with enum types, you were probably trying to assign something like an input string to the constants you defined as an enum type earlier.

let's say you created an enum type called PoliticianType

enum PoliticianType
            knownothing = 1000,
            whig = 1010,
            federalist = 1020,
            republican = 1030,
            democrat = 1040


...and you had a console app that was accepting user input from a readline statement:

            Console.Write("Which political party? (press CTRL+Z to exit): ");
            string political_party = Console.ReadLine();

... you may try to assign the input string to the constant's string value...

         PoliticianType party = political_party;

If you did try that, you would get the error that took you to this page.

It's the pairing of the constant/numeric values that caused the trouble. You'll have to convert the values to the same types. Here's what would fix it:

  PoliticianType party = (PoliticianType)Enum.Parse(typeof(PoliticianType), political_party, true);

This conversion should get you back on track!


For more on enum types, check out this article!