0

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;
    }
}
abhi
  • 3,082
  • 6
  • 47
  • 73

2 Answers2

2

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
  • 12,251
  • 8
  • 58
  • 92
  • Obviously this needs to be taken a lot further depending on what you're trying to do. – Jon Seigel Oct 04 '10 at 23:36
  • You don't need the flags attribute to use bitwise operators on enumerated values. – Ed S. Oct 04 '10 at 23:43
  • @EdS: True, but if `[Flags]` is removed, you don't get `History, Math` back as output, which is helpful when debugging. – Jon Seigel Oct 04 '10 at 23:47
  • 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 S. Oct 05 '10 at 00:00
1

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 S.
  • 122,712
  • 22
  • 185
  • 265
  • 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 S. Oct 04 '10 at 23:34
  • 1
    I am not sure it falls in the realm of nonsense. I was trying to illustrate the cast and not the function. – abhi Oct 04 '10 at 23:37
  • 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 S. Oct 04 '10 at 23:42