0

I'm trying to create an object with enum. I have to create ice creams in a class IceCream where the flavors are chocolate and vanilla, strawberry. As I have to create many of them with different flavors (among other things), I thought in these (as I've saw):

enum Flavors { Chocolate = 1, Vanilla = 2, Strawberry = 3};

class IceCream{ public int type; //if it has two o more flavors public Flavors flavor; public IceCream(int type, Flavors flavor){ this.type = type; this.Flavors = flavor; } }

Then, I want to show in console what flavor is my ice cream. How I can create an object and show in console what flavor is?

Thanks

2
  • Can you mix flavors? Like chocolate and vanilla? Commented Mar 26, 2015 at 12:45
  • It can be, but I don't know how I can do that. Commented Mar 26, 2015 at 13:00

3 Answers 3

3

You can find useful the [Flags] attribute, so you can combine two or more values, like below:

class Program
{
    static void Main(string[] args)
    {
        var iceCream = new IceCream(Flavor.Chocolate | Flavor.Vanilla);
        Console.WriteLine("{0} has {1} flavors", 
            iceCream.Flavors, iceCream.FlavorCount);
    }
}

[Flags]
enum Flavor
{
    Chocolate   = 1 << 0,
    Vanilla     = 1 << 1, 
    Strawberry  = 1 << 2
};

class IceCream
{
    public Flavor Flavors { get; private set; }
    public int FlavorCount
    {
        get
        {
            return Enum.GetValues(typeof(Flavor)).Cast<Flavor>()
                       .Count(item => (item & this.Flavors) != 0);
        }
    }

    public IceCream() { }
    public IceCream(Flavor flavors)
    {
        this.Flavors = flavors;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

what's wrong with the obvious?

var obj = new IceCream(1, Flavors.Vanilla);
Console.WriteLine(obj.Flavors);

1 Comment

Sorry, I'm a beginner
-1

You can override the base.ToString() like that:

public override string ToString()
{
   return "Flavor is: " + flavor.ToString();
}

4 Comments

This does not appear to answer the question asked at all.
Edit: The idea is to override the ToString().
The question is how to create an object from the enum. This has literally nothing to do with that
"Then, I want to show in console what flavor is my ice cream"

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.