Maximus Decimus
Maximus Decimus

Reputation: 5271

How to use switch statement with Enumerations C#

I want to use a switch statement in order to avoid many if's. So I did this:

        public enum Protocol
        {
             Http,
             Ftp
        }

        string strProtocolType = GetProtocolTypeFromDB();

        switch (strProtocolType)
        {
            case Protocol.Http:
                {
                    break;
                }
            case Protocol.Ftp:
                {
                    break;
                }
        }

but I have a problem of comparing an Enum and a String. So if I added Protocol.Http.ToString() there is another error because it allows only CONSTANT evaluation. If I change it to this

        switch (Enum.Parse(typeof(Protocol), strProtocolType))

It's not possible also. So, it's possible to use in my case a switch statement or not?

Upvotes: 2

Views: 535

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062840

As an alternative using the generic API:

Protocol protocol;
if(Enum.TryParse(GetFromProtocolTypeFromDB(), out protocol)
{
    switch (protocol)
    {
        case Protocol.Http:
            {
                break;
            }
        case Protocol.Ftp:
            {
                break;
            }
        // perhaps a default
    }
} // perhaps an else

Although frankly, it might be easier just to test with == or string.Equals (if you want case-insensitivity, etc) rather than using switch.

Upvotes: 2

Siarhei Tyshkavets
Siarhei Tyshkavets

Reputation: 392

Have you tried this:

    public enum Protocol
    {
         Http,
         Ftp
    }

    string strProtocolType = GetFromProtocolTypeFromDB();
    Protocol protocolType = (Protocol)Enum.Parse(typeof(Protocol), strProtocolType);

    switch (protocolType)
    {
        case Protocol.Http:
            {
                break;
            }
        case Protocol.Ftp:
            {
                break;
            }
    }

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73462

You need to cast the Enum.Parse result to Protocol to make it work.

switch ((Protocol)Enum.Parse(typeof(Protocol), strProtocolType))

Upvotes: 3

Related Questions