hsim
hsim

Reputation: 2080

Having trouble to assign a value from an enum in a switch loop

In my model, I have this enum that looks like this:

public enum m_ItemType
{
    Unknown = 0,
    //
    Physical = 1,
    //
    Logical = 2,
}

And I have this method which builds a list of items based on another list of item which has this enum value:

private static List<ItemType> BuildListItem(IEnumerable<ItemToSend> listItemToSend)
{
     List<ItemType> listItemsToReturn = new List<ItemType>();

     foreach (var item in listItemToSend)
     {
          ItemType itemToAdd = new ItemType();

          itemToAdd.Title = item.m_Title;
          itemToAdd.Description = item.m_Description;

          switch (item.m_ItemType)
          {
              case 0:
                 itemToAdd.Type = AnotherEnumValue.Unknown;
                 break;
              case 1:
                 itemToAdd.Type = AnotherEnumValue.Physical;
                 break;
              case 2:
                 itemToAdd.Type = AnotherEnumValue.Logical;
                 break;
          }    

          listItemsToReturn.Add(itemToAdd);
     }

     return listItemsToReturn;
}

But the code does not compile and keep telling me that the enum name is not valid at this point. Can anyone explain me why? I don't get it.

Upvotes: 0

Views: 2017

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149040

If the data type of item.m_ItemType is m_ItemType, first I would rename that to something a bit more sensible (ItemType should work). Then you need to use that name in the case statements of your switch. Try this:

// your enum
public enum ItemType
{
    Unknown = 0,
    //
    Physical = 1,
    //
    Logical = 2,
}

// your model
public class ItemToSend
{
    public ItemType m_ItemType { get; set; }
}

// in your action
private static List<ItemType> BuildListItem(IEnumerable<ItemToSend> listItemToSend)
{
    ...
    switch (item.m_ItemType)
    {
        case ItemType.Unknown:
            itemToAdd.Type = AnotherEnumValue.Unknown;
            break;
        case ItemType.Physical:
            itemToAdd.Type = AnotherEnumValue.Physical;
            break;
        case ItemType.Logical:
            itemToAdd.Type = AnotherEnumValue.Logical;
            break;
    } 
    ...
}   

Upvotes: 2

Impworks
Impworks

Reputation: 2818

In your first example the enum is named m_ItemType, but should rather be AnotherEnumValue.

Therefore, in the line switch (item.m_ItemType) the value after the dot is interpreted as a type name, not a field.

Upvotes: 1

Related Questions