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

2 Answers 2

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; } } 
Sign up to request clarification or add additional context in comments.

4 Comments

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

3 Comments

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.
I am not sure it falls in the realm of nonsense. I was trying to illustrate the cast and not the function.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.