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.
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().
“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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With