tags:

views:

60

answers:

2

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;
    }
}
+1  A: 

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;
}
Ed Swangren
That's just an example. :)
abhi
Yes, but the better the example the better your answers will be. Nonsense examples aren't helpful when you are asking people to answer a question.
Ed Swangren
I am not sure it falls in the realm of nonsense. I was trying to illustrate the cast and not the function.
abhi
Well, ok, perhaps 'nonsense' was overly harsh. My point is that I could possibly offer a better solution entirely if you were showing a practical example.
Ed Swangren
+2  A: 

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;
    }
}
Jon Seigel
Obviously this needs to be taken a lot further depending on what you're trying to do.
Jon Seigel
You don't need the flags attribute to use bitwise operators on enumerated values.
Ed Swangren
@EdS: True, but if `[Flags]` is removed, you don't get `History, Math` back as output, which is helpful when debugging.
Jon Seigel
Yes, that's true, you get the numerical values. There is a good comment about this here: http://stackoverflow.com/questions/8447/enum-flags-attribute
Ed Swangren