AJ_83
AJ_83

Reputation: 299

convert string property of list to enum

How can I convert my list Letter string property Size to an enum correctly?

Customer.Letter.Size is type string.

Customer.Letter[i].Size = (BusinessObjects.CONSTANTS.E_Letters)BusinessObjects.CONSTANTS.dict[Customer.Letter[i].Size];//i variable declared in an for loop

That is my enum:

public enum E_Size {
    small = 1,
    medium = 2,
    big = 3
}

Here my dictionary:

    public static Dictionary<string, E_Size> dict = new Dictionary<string, E_Size> {
        { "small", E_Size.small},
        { "medium", E_Size.medium},
        { "big", E_Size.big}
    };

Upvotes: 0

Views: 129

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

Why not using standard Enum.Parse?

  String source = "small"; 
  // E_Size.small 
  E_Size size = (E_Size) (Enum.Parse(typeof(E_Size), source));

Reverse conversion (from E_Size to String) either

  E_Size source = E_Size.small;
  String result = source.ToString();

or

  E_Size source = E_Size.small;
  String result = Enum.GetName(typeof(E_Size), source);

Upvotes: 2

Antonio Pelleriti
Antonio Pelleriti

Reputation: 859

convert to string, not to enum:

Customer.Letter[i].Size = BusinessObjects.CONSTANTS.dict[Customer.Letter[i].Size].ToString();

Upvotes: 1

Related Questions