0

For example, let be enum and let us loop over it

enum Main_menu { NewGame, Options, AboutAuthor, Exit }
    static void Main(string[] args)
    {

        int k = 0;
        foreach (Main_menu item in Enum.GetValues(typeof(Main_menu)))
        {
            Console.Write($"{k} ");
            Console.Write(item);
            Console.WriteLine();
            k++;
        }
        Console.ReadLine();


    }

This enum represents very simple type menu, in the program i work on, i have to use this kind of menus a several times, so i prefer to add it in a separate function, by targeting the part of code with loop and using hotkeys Ctrl+Dot i received following:

enum Main_menu { NewGame, Options, AboutAuthor, Exit }
    static void Main(string[] args)
    {

        int k = 0;
        k = LoopOverEnum(k);
        Console.ReadLine();


    }

    private static int LoopOverEnum(int k)
    {
        foreach (Main_menu item in Enum.GetValues(typeof(Main_menu)))
        {
            Console.Write($"{k} ");
            Console.Write(item);
            Console.WriteLine();
            k++;
        }

        return k;
    }
}

Now, I want to add enum Main_menu as variable, so, i will be able to apply this loop over every defined enums, I try to do it as follows:

namespace ConsoleApp11
{
class Program
{
    enum Main_menu { NewGame, Options, AboutAuthor, Exit }
    static void Main(string[] args)
    {

        int k = 0;
        k = LoopOverEnum(k, Main_menu);
        Console.ReadLine();


    }

    private static int LoopOverEnum(int k, enum Main_menu)
    {
        foreach (Main_menu item in Enum.GetValues(typeof(Main_menu)))
        {
            Console.Write($"{k} ");
            Console.Write(item);
            Console.WriteLine();
            k++;
        }

        return k;
    }
}
}

But the function's code becomes fully red with different errors. The questions are:

1) How to write the function that loops over enum, in sence that enum is variable ?

2) How to use space in definition of the enum terms ?

7
  • How to use space in definition of the enum terms please clarify this Commented Jan 2, 2019 at 4:18
  • 2
    You cannot Have spaces in the Enum value Names. @TheGeneral - He wants Enum items like: First Value = 0, Second Value = 1.... So spaces in the Name Identifier. Commented Jan 2, 2019 at 4:19
  • Since you know what parameters GetValues method takes it is unclear why code shows such a strange ‘enum Main_menu’ parameter Commented Jan 2, 2019 at 4:21
  • k = LoopOverEnum(k, Main_menu); --- You cant pass Enum Name as the parameneter here. Create a variable for it like var obj = new Main_menu(); then pass this variable in the LoopOver method Commented Jan 2, 2019 at 4:27
  • 1
    This may be a possible duplicate of stackoverflow.com/questions/7966102/… Commented Jan 2, 2019 at 4:39

4 Answers 4

1

k should not be a local variable in Main. It should be a local variable in LoopOverEnum.

There are two ways to pass a type to a method. Your attempt of LoopOverEnum(int k, enum Main_menu) is a good try but is unfortunately not valid C#.

You can either:

  • use a generic type parameter:

    public static void LoopOverEnum<T>()
        int k = 0;
        foreach (T item in Enum.GetValues(typeof(T)))
        {
            Console.Write($"{k} ");
            Console.Write(item);
            Console.WriteLine();
            k++;
        }
    }
    // usage:
    LoopOverEnum<Main_menu>()
    
  • use a parameter of type Type:

    public static void LoopOverEnum(Type type)
        int k = 0;
        foreach (var item in Enum.GetValues(type))
        {
            Console.Write($"{k} ");
            Console.Write(item);
            Console.WriteLine();
            k++;
        }
    }
    
    // usage:
    LoopOverEnum(typeof(Main_menu))
    
Sign up to request clarification or add additional context in comments.

Comments

0

Here's a generic way to Loop over Enums:

static void IterateEnum<T>(T enumSource)
{
    foreach(var item in Enum.GetValues(typeof(T)))
    {
        Console.WriteLine(item);
    }
}

Comments

0
public static IEnumerable<T> GetValues<T>() => Enum.GetValues(typeof(T)).Cast<T>();

Usage:

foreach (Main_menu item in GetValues<Main_menu>())
    MessageBox.Show(item.ToString());

Comments

0

To iterate over enum of any type And To have spaces in enum values

you can use description attribute as shown below. You can get the values mentioned in descriptionAttribute using the below method. Method is generic and hence can be used with any enum.

using System.ComponentModel; 

public enum MyEnum 
{ 
    [Description("value 1")] 
    Value1, 

    [Description("value 2")]
    Value2, 

    [Description("value 3")]
    Value3
}


public static string GetDescription<T>( T e) 
{
      if (e is Enum)
      {
         Type type = e.GetType();
         Array values = System.Enum.GetValues(type);

         foreach (int val in values)
         {
              if (val == e.ToInt32(CultureInfo.InvariantCulture))
              {
                   var memInfo = type.GetMember(type.GetEnumName(val));
                   var descriptionAttribute = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;

                if (descriptionAttribute != null)
                {
                      return descriptionAttribute.Description;
                 }
            }
        }
     }

      return null; // could also return string.Empty
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.