Search 
DailyCoding > General

Enum coversion operations (int to enum, enum to int, string to enum, enum to string)

how to to various enum coversions like int to enum, enum to int, string to enum, enum to string
Author admin on Jun 4, 2008 1 Comments
Rate it    (Rated 4 by 3 people)
2,800 Views

This post describes how can we convert enum into different data types. These are very often used operation. This is very simple to achieve thing. Let take an exmaple

public enum EmloyeeRole
{
  None = 0,
  Manager = 1,
  Admin = 2,
  Operator = 3
}

enum to int

To convert a enum to interger simply type cast the enum into integer

EmloyeeRole role = EmloyeeRole.Manager;
int roleInterger = (int)role;

int to enum

Same like above, simply type cast the integer to enum

int roleInterger = 2;
EmloyeeRole role = (EmloyeeRole)roleInterger;

string to enum

If you have string value and you want to type cast that into enum, then you can use Enum.Parse

string roleString = "Operator";
EmloyeeRole role = 
  (EmloyeeRole)Enum.Parse(typeof(EmloyeeRole), roleString);

enum to string

This is the simplest one, just use the ToString method of the enum

EmloyeeRole role = EmloyeeRole.Manager;
string roleString = role.ToString();
C# | Utility

Discussion

Visual C# Kicks On Jan 13, 2009 12:09 AM
The integer one is pretty useful. I would recommend staying away from String conversions since that's the point of using Enum in the first place. Although of course there are exceptions

Leave a Comment

Name
Email Address
Web Site
© Copyright 2008 Daily Coding • All rights reserved