Converting an integer enumeration to a string

subject to the following listing:

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

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

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

but all that seems to me is "status = 0"

+4
source share
5 answers

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

In your example, you did not specify a null value, but your status variable is initialized to zero. I suspect that it has not changed from this initial value at the moment you read it. Therefore, this string representation is also 0, and you parse zero when parsing it.

+1
source

What you are looking for is Enum.Parse.

"Converts a string representation of the name or numeric value of one or more of the listed constants into 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); 

Provided by http://blogs.msdn.com/tims/archive/2004/04/02/106310.aspx

+4
source

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

+3
source

Just use ToString () for the enumeration object

+2
source

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

 string status = Enum.GetName(typeof(DomainModel.LeadStatus), Model.Status); 
+1
source

Source: https://habr.com/ru/post/1305474/


All Articles