-1
namespace ChemicalTest
{

    enum Echemicals { oxygen, hydrogen, carbon }

    public class Chemicals
    {
        int[] chemicals = new int[3];

        public Chemicals()
        {
            foreach (int i in chemicals)
            {
                int[i] = //How can I reference each enumeration here?
                         //For example (pseudocode) - (i)Echemicals
            }
        }
    }
}

I have three enum values: oxygen {0}, hydrogen{1}, carbon{2}

I'd like to put each of these enums into an array to later be referenced by their own number, so that I could call them from the array.

I can use (int)Echemicals.hydrogen to return the default value of the second enumeration {1} but I don't know how to do this in reverse.

I am trying to store each of the names of the chemicals in an array by calling them by their integer value.

Jojo
  • 11
  • 4
  • I'm very confused about the purpose of what you're trying to do. But to answer your question, you just cast the int to the enum type like `(Echemicals)1` will give you `Echemicals.hydrogen`. – itsme86 Nov 10 '17 at 14:09
  • 1
    What is your actual requirement? I think you are confused and try to make us also confused – sujith karivelil Nov 10 '17 at 14:10

3 Answers3

0

You just need to cast to your enum:

Echemicals val = (Echemicals)i;

But you don't need to use int[] for this. Maybe you should give more details as to what the issue is.

Ric
  • 12,855
  • 3
  • 30
  • 36
0

I believe it is easier if you do it the other way around, first get all enums and than cast them to integer:

var enumValues = Enum.GetValues(typeof(Echemicals));
var decimals = enumValues.OfType<Echemicals>().Select(x => (int)x).ToArray();
Rand Random
  • 7,300
  • 10
  • 40
  • 88
0

You can do something like this:

enum Echemicals { 
    oxygen = 1, 
    hydrogen = 2, 
    carbon = 3 
}
// ...
int oxigenInt = (int) Echemicals.oxygen;
Echemicals oxigenEnum = (Echemicals) 1;

Alternatively you can use the Immutable Object Design:

public class Echemicals {
    private int index;

    private Echemicals(int index) {
        this.index = index;
    }

    public static Echemicals _Oxygen = new Echemicals(1);
    public static Echemicals Oxygen { get { return _Oxygen; } }

    // Other elements

    // A list of all values:
    public static Echemicals[] _Values;
    public static Echemicals[] Values { get { return _Values; } }

    static Echemicals() {
        _Values = new[] {Oxygen, /*other elements*/};
    }

    static Echemicals GetByIndex(index) {
        return Values.FirstOrDefault(e => e.index == index);
    }
}

A lot more work, but useful if you need more properties in that element other than just the index.

Maglethong Spirr
  • 433
  • 1
  • 5
  • 15