one.beat.consumer
one.beat.consumer

Reputation: 9504

Parsing mixed value enums (char and int)

I have an oddball enum where some of the values are char and others int:

public enum VendorType{
    Corporation = 'C',
    Estate = 'E',
    Individual = 'I',
    Partnership = 'P',
    FederalGovernment = 2,
    StateAgencyOrUniversity = 3,
    LocalGovernment = 4,
    OtherGovernment = 5
}

I'm yanking in some data from a text file that provides the symbol for this type (ex. I or 4), and I use that to lookup the enum's hard typed value (ex. VendorType.Individual and VendorType.LocalGovernment respectively).

The code i am using to do this is:

var valueFromData = 'C'; // this is being yanked from a File.IO operation.
VendorType type;
Enum.TryParse(valueFromData, true, out type);

So far so good when it comes to parsing the int values... but when I try to parse the char values the type variable doesn't parse and is assigned 0.


Question: Is it possible to evaluate both char and int enum values? If so, how?

Note: I do not want to use custom attributes for assigning text values like I've seen in some other hack-ish examples online.

Upvotes: 1

Views: 5813

Answers (1)

Mark Byers
Mark Byers

Reputation: 838256

Your enum has int as its underlying type. All the values are ints - the characters are converted to integers. So VendorType.Corporation has the value (int)'C' which is 67.

See it online: ideone

To convert a character to a VendorType you just need to cast:

VendorType type = (VendorType)'C';

See it working online: ideone


EDIT: The answer is correct, but I am adding the final code it took to get this working.

// this is the model we're building
Vendor vendor = new Vendor(); 

// out value from Enum.TryParse()
VendorType type;

// value is string from File.IO so we parse to char
var typeChar = Char.Parse(value);

// if the char is found in the list, we use the enum out value
// if not we type cast the char (ex. 'C' = 67 = Corporation)
vendor.Type = Enum.TryParse(typeChar.ToString(), true, out type) ? type : (VendorType) typeChar;

Upvotes: 10

Related Questions