Ask Paula!

...bringing you notes from the field...
posts - 117 , comments - 87 , trackbacks - 0

My Links

News

Copyright © 2008-2014 Paula DiTallo

Tag Cloud

Article Categories

Archives

Post Categories

Image Galleries

.NET Development

Enterprise Integration

Entertainment - Games

Java Development

Mobile/PDA Development

Professional Affiliations

Why did I get the error: Cannot implicitly convert type 'string' to 'yourEnumDef.type' in my C# program?

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!

Print | posted on Saturday, August 28, 2010 11:34 PM | Filed Under [ Enterpise Architecture Practical Answers .NET ]

Feedback

Gravatar

# re: Why did I get the error: Cannot implicitly convert type 'string' to 'yourEnumDef.type' in my C# program?

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
8/31/2010 11:18 AM | Ryan
Gravatar

# UPDATE: Why did I get the error: Cannot implicitly convert type 'string' to 'yourEnumDef.type' in my C# program?

Thanks for posting the Enum.TryParse() ref Ryan!:-)
8/31/2010 3:48 PM | Paula DiTallo
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: