1

I am using an enum that was created in c#:

public enum ParamChildKey
{
    [EnumMember(Value = "SYS")]
    System,
    [EnumMember(Value = "GAT")]
    Gate,
    [EnumMember(Value = "CRT")]
    Create,
    [EnumMember(Value = "FLT")]
    Fault,
}

I am writing code in vb.net and have a vb.net String, say "CRT" that I am trying to match up with its enum so I can pass the enum into a function.

When I write ParamChildKey.Create.ToValue I get a string value of "CRT" however when I use [Enum].GetValues it returns the integer index of each enum, "2" in this case.

My question is how do I get the enum by matching a string value to it so I can pass the enum into a function? So if I have a string value of "CRT" how do I get ParamChildKey.Create from the "CRT" string value? In this example I will be passing in ParamChildKey.Create into the function below.

GetParameterValue(paramName As Integer, Optional paramChildKey As ParamChildKey = ParamChildKey.System)
1

2 Answers 2

1

EnumMemberAttribute is used for serialization purposes. So it's not useful in your scenario.

IMO simplest solution would be writing a swtich-case statement.

switch(textValue){
    case "CRT":
       return ParamChildKey.Create;
    ...
}

If you have a dynamic set of enumerations which change over time, you can use System.Reflection library but this performs much worse than statically written and compiled code.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought I may just have to use a Select-Case statement. I was hoping there was a way around it. I am stuck on .NET 3.5 right now so TryParse isn't available to me.
0

To convert an string to an enum, use the [Enum].TryParse method which is available in .NET 4.

Dim p As ParamChildKey
If [Enum].TryParse("CRT", p) Then
    Console.WriteLine(p)
    Console.WriteLine(p.ToString())
End If

If using .NET 3.5 or below, you can use this version https://stackoverflow.com/a/1082587/3230456

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.