Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select an enum value from the string representation of the 'name'?

Tags:

c#

enums

I have enum like this

public enum PetType
{
    Dog = 1,
    Cat = 2
}

I also have string pet = "Dog". How do I return 1? Pseudo code I'm thinking about is:

select Dog_Id from PetType where PetName = pet
like image 227
user194076 Avatar asked Nov 16 '11 00:11

user194076


People also ask

How do you find the enum of a string representation?

The Java Enum has two methods that retrieve that value of an enum constant, name() and toString(). The toString() method calls the name() method, which returns the string representation of the enum constant.

How do you find the value of an enum?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do you enum a string?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

Can we give string value in enum?

As you can see, it's pretty easy to decorate your enum values with string descriptions. This allows you to use a central location to set the value. I can even see a custom description attribute class that retrieves the description from a database. The use cases are there.


1 Answers

Use the Enum.Parse method to get the enum value from the string, then cast to int:

string pet = "Dog";
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet);
int petValue = (int)petType;
like image 95
Thomas Levesque Avatar answered Sep 18 '22 04:09

Thomas Levesque