Ask Paula!

...bringing you notes from the field...

  Home  |   Contact  |   Syndication    |   Login
  147 Posts | 5 Stories | 133 Comments | 0 Trackbacks


Copyright © 2008-2018 Paula DiTallo

Tag Cloud


Post Categories

.NET Development

Enterprise Integration

Entertainment - Games

Java Development

Mobile/PDA Development

Professional Affiliations

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!

posted on Saturday, August 28, 2010 11:34 PM


# re: Why did I get the error: Cannot implicitly convert type 'string' to 'yourEnumDef.type' in my C# program? 8/31/2010 11:18 AM Ryan
Check out the Enum.TryParse() method. It won't throw an exception when the string doesn't match an enum value.

# UPDATE: Why did I get the error: Cannot implicitly convert type 'string' to 'yourEnumDef.type' in my C# program? 8/31/2010 3:48 PM Paula DiTallo
Thanks for posting the Enum.TryParse() ref Ryan!:-)

Post A Comment