Geeks With Blogs
David Douglass .NET on My Mind

Enumerated constants in C# can be represented 3 different ways:

  1. as a C# program constant
  2. as a number (typically int)
  3. as a string spelled identically to the C# constant

Here a sample program demonstrating how to convert between any of these formats.

using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication2 { public enum Color { red, white, blue } class Program { static void Main(string[] args) { string toString, fromString = "red"; int toInt, fromInt = 1; Color toColor, fromColor = Color.blue; // string to enum toColor = (Color) Enum.Parse(typeof(Color), fromString); // string to int toInt = (int) (Color) Enum.Parse(typeof(Color), fromString); // int to enum toColor = (Color) fromInt; // int to string toString = ((Color) fromInt).ToString(); // enum to string toString = fromColor.ToString(); // enum to int toInt = (int) fromColor; Console.ReadLine(); } } }
Posted on Thursday, February 25, 2010 7:02 PM | Back to top


Comments on this post: Round & Round with Enums

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © David Douglass | Powered by: GeeksWithBlogs.net