Enum conversion in C#

Just for reference, here are some examples on how enums can be converted in C#:

public class MyAnimalClass
{
    public enum Animal
    {
        Cat = 1,
        Dog = 2,
        Bird = 3
    }

    // enum to string
    public void Hey()
    {
        Animal animal = Animal.Bird;
        string animalText = animal.ToString(); // Bird

        HttpContext.Current.Response.Write("<br />enum to string : " + animalText);
    }

    // string to enum
    public void Hey2()
    {
        string animalText = "cat";
        Animal animal;
        // Enum.TryParse will return false if the string value cannot be converted to the enum type
        if (!Enum.TryParse<Animal>(animalText, out animal))
            HttpContext.Current.Response.Write("<br />string to enum is null for : " + animalText);
        else
            HttpContext.Current.Response.Write("<br />string to enum: " + animal.ToString()); // Animal.Cat

        Animal animal2 = (Animal)Enum.Parse(typeof(Animal), animalText, true); // Animal.Cat (case insensitive comparison)

        HttpContext.Current.Response.Write("<br />string to enum insensitive: " + animal2.ToString());
    }

    // int to enum
    public void Hey3()
    {
        int animalInt = 2;
        Animal animal = (Animal)animalInt;

        HttpContext.Current.Response.Write("<br />int to enum : " + animal.ToString());
    }

    // enum to int
    public void Hey4()
    {
        Animal animal = Animal.Bird;
        int animalInt = (int)animal;

        HttpContext.Current.Response.Write("<br />enum to int : " + animalInt.ToString());
    }
}

Using enums when coding makes life easier as you can easily tell what sort of object you’re dealing with rather than having to guess what the numbers (1,2,3, etc) mean really.

comments powered by Disqus