Using foreach to loop through the elements of an enumeration in .Net (C#)

If you find yourself in need of looping through the elements of an enumeration
and do something for each of them then you may want to take a look at the following code:

enum Elements {
        Manganese,         Chrome,         Gold,         Argon
// we cannot loop through the enumeration but we can through an array of strings
// representing the name of the elements of that enumeration,
// which is what Enum.GetNames() method will gladly give us if we pass the type of the enumeration

foreach (string elementName in Enum.GetNames(typeof(Elements))) {
    // then, if we need to create an instance of the enumeration type based on the
    // current elementName we use Enum.Parse() method which takes:
    //  - the type of the enumeration and
    //  - the elementName (a string);
    //  Enum.Parse() returns <object> so we have to explicitly cast it to our enumeration type

    Elements element = (Elements)Enum.Parse(typeof(Elements), elementName);

so, the above foreach loops four times and in each iteration you have access to an element
of the enumeration as its native type and as a string representation – its name.