9

I have implemented the enum below:

public enum CaseOriginCode
{
    Web = 0,
    Email = 1,
    Telefoon = 2
}

I would like to get the enum int value by a string. Something like this:

public void setCaseOriginCode(string caseOriginCodeParam)
{
    int caseOriginCode = CaseOriginCode.GetEnumByString(caseOriginCodeParam);
    // do something with this integer
}

So my input is a string and my output needs to be an int.

Or is it better to implement an dictionary with an key value. The key will be the string and the will be an int.

0

3 Answers 3

13

Please try with the below code snippet.

public void setCaseOriginCode(string CaseOriginCode)
{
    int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}

Let me know if any concern.

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

Comments

0

One thing to note, if after casting you are getting a result of 0, then it is likely because you did not specify a value for your enum.

For example, change this:

public enum AcquisitionChannel
{
    Referal,
    SearchEngines,
    SocialMedia
}

to

public enum AcquisitionChannel
{
    Referral = 1,
    SearchEngines = 2,
    SocialMedia = 3
}

Comments

-2

If I understand this question correctly why not just use a switch case?

public CaseOriginCode setCaseOriginCode(string caseOriginCodeParam)
{
    switch(caseOriginCodeParam)
    {
        case "Web":
            return CaseOriginCode.Web;
        case "Email":
            return CaseOriginCode.Email;
        case "Telefoon":
            return CaseOriginCode.Telefoon;
        default:
            return default(CaseOriginCode);
    }
}

So in practice it would be something like this...

int x = (int)setCaseOriginCode("Web"); // output would be 0
CaseOriginCode y = setCaseOriginCode("Email"); // output would be CaseOriginCode.Email

2 Comments

Horrible practice! If you ever add another enum member, you have to remember to update it here as well! This should never be done!
@SerjSagan Yes, you have to remember... but if you want to have more logic behind the return you might want to do it this way anyway... and if you are constantly adding to your enum you probably don't want an enum anyway?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.