Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with multiple enumeration types in one variable

Tags:

c#

I don't know if this is possible or not, but I'm writing a simple game using XNA and C#, and somehow need one particular variable to be able to handle more than one enumeration type. The character you control has a single inventory slot, which can be one of the fruit types below:

public enum Fruit : int {Apple, Banana, Orange};
public Fruit carrying;

But the character can also be able to carry something else:

public enum Misc : int {Parcel, Brush};

I don't want to merge them all into one enum because I want the Fruit enumeration to be distinct, and I don't want to have to have two different 'carrying' variables - one for Fruit and one for Misc.

Is there any way of having, say, a super-enumeration, that can merge them together into a third enumeration of all five members?

EDIT: thanks for the responses. I have decided to create a single Item type (a member of which is an enumeration that differentiates between Fruit and Misc) and load them into a List via XML.

like image 514
EvoluZion3 Avatar asked Feb 23 '14 09:02

EvoluZion3


People also ask

How do you fix multiple enumeration of IEnumerable?

This kind of problem can be easily fixed — force the enumeration at the point of variable initialization by converting the sequence to an array or a list, for example: List<string> names = GetNames().

Why is multiple enumeration bad?

“Possible multiple enumeration of IEnumerable“ is a resharper warning. If you enumerate an enumerable more than once, ReSharper will detect this and warn you about it. Although this warning may seem pointless at first, there are two good reasons to pay attention to it: Enumerating an enumerable can be very expensive.


1 Answers

It sounds like you probably want a union type for CarriableItem or something similar. For example:

public sealed class CarriableItem
{
    public Fruit? Fruit { get; private set; }
    public Misc? Misc { get; private set; }

    // Only instantiated through factory methods
    private CarriableItem() {}

    public static CarriableItem FromFruit(Fruit fruit)
    {
        return new CarriableItem { Fruit = fruit };
    }

    public static CarriableItem FromMisc(Misc misc)
    {
        return new CarriableItem { Misc = misc };
    }
}

You might also then want another enum to indicate which kind of item is being carried:

public enum CarriableItemType
{
    Fruit,
    Misc
}

Then add a property to CarriableItem:

public CarriableItemType { get; private set; }

and set it in the factory methods appropriately.

Then your person would have just a single variable of type CarriableItem.

like image 190
Jon Skeet Avatar answered Sep 19 '22 14:09

Jon Skeet