Home > Mobile >  How can I make this generic and pass any enum to it?
How can I make this generic and pass any enum to it?

Time:07-21

Okay, it's time I learned arguments, parameters, generics... Oh yay me!! I see how to use explicit typing but have no clue as to making this method generic and pass in the enum of choice. Any advice/"tutor code" would be great.

using System;

public class Program

{
    enum FarmAnimals { Cow = 1, Chicken, Goat, Horse }
    
    enum ForrestAnimals { Lion = 1, Tiger, Elephant, Panther, Monkey }

    enum SeaAnimals{ Whale = 1, Shark, Eel, Tuna, Swordfish, Dolphin, Sealion }

    public static void Main()
    
    {
        Test();
    }

    static void Test()
    {
        bool whatever = true;
        bool ok;
        int pick = 0;

        foreach (FarmAnimals animals in Enum.GetValues(typeof(FarmAnimals)))
        {
            int id = Convert.ToInt32(animals);
            String name = Enum.GetName(typeof(FarmAnimals), animals);
            Console.WriteLine("{0} - {1}", id, name);
        }

        while (whatever == true)
        {
            Console.Write("Pick a number ");
            String line = Console.ReadLine();
            ok = int.TryParse(line, out pick);

            if (ok)
            {
                int counter = Enum.GetValues(typeof(FarmAnimals)).Length;
                if (pick < 1 || pick > counter)
                {
                    Console.WriteLine("You have an invalid number! You used {0}.", pick);               
                }
                else
                {
                    FarmAnimals animals = (FarmAnimals)pick;
                    Console.WriteLine("Great! You picked: {0}", animals);
                    
                }
            }
            else
            {
                Console.WriteLine("Please pick a number.");     
            }
        }

    }
}

CodePudding user response:

Your code have endless loop. There must be an exit condition.

Bellow code remove endless loop and use generic method, You can pass any enum to it

public static void Test<T>() where T : Enum
{
    Type enumType = typeof(T);

    foreach (T enumValue in Enum.GetValues(enumType))
        Console.WriteLine("{0} - {1}", Convert.ToInt32(enumValue), Enum.GetName(enumType, enumValue));

    while (true)
    {
        Console.Write("Pick a number ");
        string line = Console.ReadLine();
        int pick;

        bool ok = int.TryParse(line, out pick);

        if (ok)
        {
            if (pick < 1 || pick > Enum.GetValues(enumType).Length)
                Console.WriteLine("You have an invalid number! You used {0}.", pick);
            else
                Console.WriteLine("Great! You picked: {0}", Enum.GetName(enumType, pick));

            break;
        }

        Console.WriteLine("Please pick a number.");
    }
}

And then, you can use it like this

Test<SeaAnimals>();
Test<ForrestAnimals>();
  • Related