Moe R
Moe R

Reputation: 73

Convert output of string to a number value

I have the following code

Call.Direction CallDir = details.dir; 

and the output is either In or out.

my question how can I convert the output to be as follow:

Upvotes: 3

Views: 46

Answers (2)

Josh
Josh

Reputation: 44906

In addition to what Michael said, if your enum is defined with the appropriate values, you can simply cast it to an int.

enum CallDirection { In = 0, Out = 1 }

var dir = CallDirection.In;

Console.Write((int)dir); // "0"

Upvotes: 2

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Okay, so if you wanted to return a different value based on the enum, just do this:

return CallDir == Call.Direction.In ? 0 : 1;

However, if what you're saying is details.dir is a string of In or Out and you need to get that into an enum, then do this:

Call.Direction CallDir;
if (!enum.TryParse<Call.Direction>(details.dir, out CallDir))
{
    // set it to some default value because it failed
}

Upvotes: 3

Related Questions