Convert a string or an integer to enum type

Something that I always use whenever I use enumeration :

public enum StatusType
	{
		Approved = 1,
		Pending = 2,
		Cancelled = 3
	}

Convert a string to enum :

string currentStatus = "Approved";
StatusType status = (StatusType) Enum.Parse(typeof(StatusType), currentStatus);

Convert an int to enum :

int currentStatusId = 1;
StatusType type = (StatusType) Enum.ToObject(typeof(StatusType), currentStatusId); 

Just be careful with enum conversion, especially when you want to use Enum.IsDefined method as it is very expensive.

2 Responses to Convert a string or an integer to enum type

  1. Orca says:

    WOWWW!! Thanks DUDEEE!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: