RMiles
RMiles

Reputation: 1

How to use enum in C# to create objects

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

Upvotes: 0

Views: 2556

Answers (3)

anon
anon

Reputation: 192

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

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

Upvotes: -1

Rubens Farias
Rubens Farias

Reputation: 57996

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;
    }
}

Upvotes: 3

DLeh
DLeh

Reputation: 24405

what's wrong with the obvious?

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

Upvotes: 0

Related Questions