Home c# foreach () for enum

foreach () for enum

Author

Date

Category

Tell me how to organize foreach () for ENUM elements?
An example of what I want to do:

Public Enum Fruits
{
    Apple,
    Orange
    Kivi.
}
Public Void EnumerateAllFruits ()
{
    foreach (Fruit In Fruits)
    {
        Dosomething (Fruit);
    }
}

Answer 1, Authority 100%

if foreach (), then:

foreach (Fruit In Enum.GetValues ​​(Fruits))
{
   Dosomething (Fruit);
}

Answer 2

If the transmission power is known (and it, of course, is known – the main thing, do not forget to correct the constant when the transfer changes), then you can, for example, so:

const int fruitscount = 3;
Public Void EnumerateAllFruits ()
{
    For (Fruits Fruit = 0; (int) Fruit & lt; Fruitscount; Fruit ++)
    {
        Dosomething (Fruit);
    }
}

It will work, because by default the elements of the listing correspond to the integers from 0 to N-1 (if you continue the Fruit ++ operation, detect that no error occurs, and Fruit will start taking unnamed values ​​3, 4, …)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions