tags:

views:

69

answers:

5

Hello.

I'm developing a C# application and I have the following enum:

public enum TourismItemType : int
{
     Destination = 1,
     PointOfInterest = 2,
     Content = 3
}

And I also have a int variable, and I want to check that variable to know it is equal to TourismItemType.Destination, like this:

int tourismType;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
    switch (tourismType)
    {
        case TourismItemType.Destination:
            ShowDestinationInfo();
            break;
        case TourismItemType.PointOfInterest:
            ShowPointOfInterestInfo();
            break;
    }
}

But it throws an error.

How can I do that?

Thanks.

+5  A: 

Cast tourismType to your enum type as there is no implicit conversion from ints.

switch ((TourismItemType)tourismType)
//...
Jeff M
+1  A: 

You can parse tourismType to your enum type using Enum.TryParse or you can treat enum values as int like: case (int)TourismType.Destination.

Adrian Faciu
+1  A: 

Try

int tourismType;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
    switch (tourismType)
    {
        case (int)TourismItemType.Destination:
            ShowDestinationInfo();
            break;
        case (int)TourismItemType.PointOfInterest:
            ShowPointOfInterestInfo();
            break;
    }
}

or

int tourismType;
TourismItemType tourismTypeEnum;
if (int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
    tourismTypeEnum = (TourismItemType)tourismType;
    switch (tourismTypeEnum)
    {
        case TourismItemType.Destination:
            ShowDestinationInfo();
            break;
        case TourismItemType.PointOfInterest:
            ShowPointOfInterestInfo();
            break;
    }
}
Irina
+2  A: 

You could also do:

int tourismType;
if ( int.TryParse(NavigationContext.QueryString.Values.First(), out tourismType )
{
    if ( Enum.IsDefined(typeof(TourismItemType), tourismType) )
    {
        switch ((TourismItemType)tourismType)
        {
            ...
        }
    }
    else
    {
        // tourismType not a valid TourismItemType
    }
}
else
{
    // NavigationContext.QueryString.Values.First() not a valid int
}

Of course you could also handle invalid tourismType in the switch's default: case.

JLWarlow
+1  A: 

If you're running .NET 4 then you can use the Enum.TryParse method:

TourismItemType tourismType;
if (Enum.TryParse(NavigationContext.QueryString.Values.First(), out tourismType))
{
    switch (tourismType)
    {
        case TourismItemType.Destination:
            ShowDestinationInfo();
            break;
        case TourismItemType.PointOfInterest:
            ShowPointOfInterestInfo();
            break;
    }
}
LukeH