abhi
abhi

Reputation: 3136

Using integer based enum

Is it possible to do the enum without having to do a cast?

class Program
{
   private enum Subject 
   { 
       History = 100, Math =200, Geography = 300
   }
    static void Main(string[] args)
    {
      Console.WriteLine(addSubject((int) Subject.History)); //Is the int cast required.
    }
    private static int addSubject(int H)
    {
        return H + 200;
    }
}

Upvotes: 0

Views: 178

Answers (2)

Jon Seigel
Jon Seigel

Reputation: 12401

I'll take a stab at part of what the business logic is supposed to be:

class Program
{
   [Flags]   // <--
   private enum Subject 
   { 
       History = 1, Math = 2, Geography = 4    // <-- Powers of 2
   }
    static void Main(string[] args)
    {
        Console.WriteLine(addSubject(Subject.History));
    }
    private static Subject addSubject(Subject H)
    {
        return H | Subject.Math;
    }
}

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124770

No, because then you would lose type safety (which is an issue with C++ enums).

It is beneficial that enumerated types are actual types and not just named integers. Trust me, having to cast once in a while is not a problem. In your case however I don't think you really want to use an enum at all. It looks like you are really after the values, so why not create a class with public constants?

BTW, this makes me cringe:

private static int addSubject(int H)
{
    return H + 200;
}

Upvotes: 1

Related Questions