-2

How can I call a method that expects an int value by using an enum member. I dont want the called method to have to know about the enum.

public enum Volume : int
{
    Low = 1,
    Medium = 2,
    High = 3
}

public void Start() {
    DoSomeWork(Volume.Low);  //this complains
    //this works  DoSomething((int)Volume.Low);

}

public void DoSomeWork(int vol) {
    //Do something
}
bitshift
  • 6,026
  • 11
  • 44
  • 108
  • 4
    You have the answer in the question yourself. Why even ask the question? Having said that, you'd be much better off having the method accept the enum. Having it accept a magic int is going to make that method very confusing for callers who need to memorize what int means what. – Servy Feb 18 '14 at 14:37

4 Answers4

3

Cast it explicitly to int (as you have already figured out):

DoSomeWork((int)Volume.Low)

Implicit conversion from enum to underlying type is forbidden, since there are a lot of cases when this conversion does not make sense. @EricLippert explains this well enough here.

However why introduce the enum if you are not using it? If the volume rate in your program is specified by the enum - then this is the type your method should expect as a parameter.

Community
  • 1
  • 1
Andrei
  • 55,890
  • 9
  • 87
  • 108
  • Yes, but id rather not. Shouldnt the compiler know that Volume.Low is of type int, especially since I set the base type of the enum? – bitshift Feb 18 '14 at 14:42
  • @bitshift, please see the update with some explanation – Andrei Feb 18 '14 at 14:44
  • Well, now that I looked it up, both the enum member and an int might be the same intregal type, they need an explicit cast to go from one to the other. http://csharp-station.com/Tutorial/CSharp/Lesson17 – bitshift Feb 18 '14 at 14:45
1

Call it like this:

DoSomeWork( (int) Volume.Low );
Tony Vitabile
  • 8,298
  • 15
  • 67
  • 123
0

Why not using this way:

public void DoSomeWork(Volume volume) {
    //Do something
}
Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
0

as documentation states

Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int.

so you can just simple cast it to int and pass it to the method that way.

DoSomeWork((int)Volume.Low);
Dimitri
  • 2,798
  • 7
  • 39
  • 59