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
Filed Under [ Enterpise Architecture Practical Answers .NET ]

Comments

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

http://msdn.microsoft.com/en-us/library/dd783499.aspx
Gravatar
# UPDATE: Why did I get the error: Cannot implicitly convert type 'string' to 'yourEnumDef.type' in my C# program?
posted by Paula DiTallo
on 8/31/2010 3:48 PM
Thanks for posting the Enum.TryParse() ref Ryan!:-)

Post A Comment
Title:
Name:
Email:
Comment:
Verification: