Ola
Ola

Reputation: 1208

Get enum int value by string

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.

Upvotes: 9

Views: 10497

Answers (3)

Serj Sagan
Serj Sagan

Reputation: 30267

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
}

Upvotes: 0

CodeCamper
CodeCamper

Reputation: 6984

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

Upvotes: -2

Jayesh Goyani
Jayesh Goyani

Reputation: 11154

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.

Upvotes: 13

Related Questions