5

considering the following enum:

public enum LeadStatus 
{ 
    Cold = 1, 
    Warm = 2, 
    Hot = 3, 
    Quote = 5, 
    Convert = 6 
} 

How can I convert the integer value back to string when I pull the value from a database. I've tried:

DomainModel.LeadStatus status = (DomainModel.LeadStatus)Model.Status;

but all I seem to get is "status = 0"

5 Answers 5

5

Given "Model.Status" is the integer from the database, it can be restored to the Enum string value with:

string status  = Enum.GetName(typeof(DomainModel.LeadStatus), Model.Status);
Sign up to request clarification or add additional context in comments.

Comments

4

What you are looking for is Enum.Parse.

"Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object."

Here is the MSDN page: http://msdn.microsoft.com/en-us/library/essfb559.aspx

Example:

enum Colour
{
   Red,
   Green,
   Blue
} 

// ...
Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);

Courtesy of http://blogs.msdn.com/tims/archive/2004/04/02/106310.aspx

2 Comments

I tried that first and it gave me the same result: DomainModel.LeadStatus status = (DomainModel.LeadStatus)Enum.Parse(typeof(DomainModel.LeadStatus), Model.Status.ToString()); status = 0
And Model.status was zero? I was wondering why it wasn't working, I think an explicit cast from integer to enum should work.
4

Between Enum.Parse and Enum.ToString, you should be able to do everything you need.

1 Comment

This is very helpful, thank you. A side note about Enum.Parse, you need to use typeof(), e.g. Enum.Parse(typeof(Colors), "blue");
3

Just use ToString() on the enum object

1 Comment

Is Model.Status also zero? Perhaps you're not reading the value back correctly from the database. ToString() should do what you want.
1

An enumeration in C# is used to provide names for some known values but ANY integer value is permissible in that enumeration, whether it has a named equivalent or not.

In your example, you have not named a zero value, but your status variable initialises to zero. I suspect that it has not changed from this initial value at the point you read it. Therefore, it's string representation is also 0 and you will parse out zero when you parse it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.