0

I can't find this question related to unidimentional enums and i think is different with bi-dimentional ones, so let's start.

Let's say i have this enum:

public enum TileType {Empty, Floor};

and i have this elements inside my class:

private TileType _type = TileType.Empty;

public TileType Type {
        get {
            return _type;
        }
        set {
            TileType oldType = _type;
                _type = value;
            }
    }

How can i get "Empty" or "Floor" using an index (int) to retreive them in C#?

And, like a side-question without any tipe of priority...

how would you retreive the information stored in 'oldType' TileType? (this sub questions, if you want it to answer it, answer it in the comments plz)

PS: Let's asume for purpose of this question than we already think than the enum is the way to go in this code, and than i already check the usefullness of other types of list.

Any improvement to this question or request for clarification would be much apreciated too

Thanks in advance

user57129
  • 309
  • 1
  • 6
  • 17
  • Thanks, i can't find that anywhere, thats just what i need. But is there anything more close to the Dictionary.GetKey() method? – user57129 Jan 19 '16 at 03:18

2 Answers2

1

Enumerations are not indexed, but they do have underlying values... in your case Empty and Floor are 0 and 1, respectively.

To reference TileType.Floor, you could use this:

var floor = (TileType)1;

Since you asked about something like Dictionary.GetKey(), there are methods available on the Enum class, but nothing exactly like that.

You could write your own extension method. Give this a try, for example:

public static class EnumExt
{
    public static T GetKey<T>(int value) where T : struct
    {
        T result;

        if (!Enum.TryParse(value.ToString(), out result))
            // no match found - throw an exception?

        return result;
    }
}

Which you could then call:

var floor = EnumExt.GetKey<TileType>(1);
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
0

Try this one, similar question I believe? Retrieve value of Enum based on index - c#

You should put your oldType as a variable outside the Type property.

Community
  • 1
  • 1
Dr. Stitch
  • 908
  • 6
  • 15
  • Thanks a lot, but the thing is that question don't help to new people with uni-dimensional enums, i guess something more "user friendly" or "newbie friendly" would help to introduce in enums before try that, in any case, thanks for your try. – user57129 Jan 19 '16 at 03:12
  • I believe this one may help you start (https://msdn.microsoft.com/en-us/library/cc138362.aspx). Enum.GetName(typeof(TileType), 1); – Dr. Stitch Jan 19 '16 at 03:18