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

1
  • Thanks, i can't find that anywhere, thats just what i need. But is there anything more close to the Dictionary.GetKey() method? Commented Jan 19, 2016 at 3:18

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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.
I believe this one may help you start (msdn.microsoft.com/en-us/library/cc138362.aspx). Enum.GetName(typeof(TileType), 1);

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.