Thursday, November 15, 2007

Enum.Parse

I had this issue, in which in one of my C# class, I had a enum type. Then I wanted to send a string to a method, which will populate this object. The problem was that the enum type was an integer, and I was passing a string down to the object.

    1 public enum ProductTypeEnum : int 
    2 {
    3     blue = 10,
    4     red = 20,
    5     green = 30
    6 } 

Here is the class that I was using to populate with values:

    1 public void GetDiscountTest_BLUE_Preferred()
    2 {
    3     OrderDetail inOrder = new OrderDetail();
    4     inOrder.ProductType = (Int32) ProductTypeEnum.blue;
    5     inOrder.Quantity = 100;

Now, I wanted to replace the code with something like this:

    1 public void GetDiscountTest_BLUE_Preferred(string sColorName)
    2 {
    3     OrderDetail inOrder = new OrderDetail();
    4     inOrder.ProductType = ConvertToEnum(sColorName);
    5     inOrder.Quantity = 100;


Here is the code to accomplish that:
    1 public void WorkingDiscount(string sColorName)
    2 {
    3     OrderDetail inOrder = new OrderDetail();
    4     inOrder.ProductType = (Int32)Enum.Parse(typeof(ProductTypeEnum), sColorName);
    5     inOrder.Quantity = 100;

now I will remember this.

No comments: