How to get the integer value of an enumeration when I only have an enumeration type

I think this question needs some code:

private TypeValues GetEnumValues(Type enumType, string description) { TypeValues wtv = new TypeValues(); wtv.TypeValueDescription = description; List<string> values = Enum.GetNames(enumType).ToList(); foreach (string v in values) { //how to get the integer value of the enum value 'v' ????? wtv.TypeValues.Add(new TypeValue() { Code = v, Description = v }); } return wtv; } 

Name it as follows:

 GetEnumValues(typeof(AanhefType), "some name"); 

In the GetEnumValues function, I have enumeration values. So I repeat the values โ€‹โ€‹and want to get the integer value of this enum value.

So my values โ€‹โ€‹are โ€œredโ€ and โ€œgreenโ€, and I also want to get 0 and 1.

When I have Enum in my function, I can create an enumeration value from a string and pass it to this enumeration, and then pass it to int, but in this case I do not have the enum itself, but only the type of the enumeration.

I tried passing in the actual enumeration as a parameter too, but I am not allowed to pass enum as a parameter.

So now I'm stuck .....

+4
source share
3 answers
 private TypeValues GetEnumValues(Type enumType, string description) { TypeValues wtv = new TypeValues(); wtv.TypeValueDescription = description; List<string> values = Enum.GetNames(enumType).ToList(); foreach (string v in values) { //how to get the integer value of the enum value 'v' ????? int value = (int)Enum.Parse(enumType, v); wtv.TypeValues.Add(new TypeValue() { Code = v, Description = v }); } return wtv; } 

http://msdn.microsoft.com/en-us/library/essfb559.aspx

Enum.Parse will take Type and String and return a reference to one of the enum values, which can then be simply converted to int.

+5
source

Try

 (int)Enum.Parse(enumType, v) 
+5
source
 public static class StringEnum { public static string GetStringValue(Enum value) { string output = null; Type type = value.GetType(); FieldInfo fi = type.GetField(value.ToString()); StringValue[] attr = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[]; if (attr.Length > 0) { output = attr[0].Value; } return output; } } 

this is a method to get a string value.

 public enum CampaignRequestType { [StringValue("None")] None = 0, [StringValue("Pharmacy Cards")] Pharmacy_Cards = 1,[StringValue("Prospect Campaign")] Prospect_Campaign = 2,[StringValue("Tradeshow/Advertising")] Tradeshow_Advertising = 3 } 

listing it ...

 string item = StringEnum.GetStringValue((Enumeration.CampaignRequestType)updateRequestStatus.RequestType_Code); 

here (Enumeration.CampaignRequestType) is my enumeration and updateRequestStatus.RequestType_Code is a database type field of type

i pour int value for enumeration type

0
source

All Articles