Scot T Brennecke <(E-Mail Removed)> wrote:
> You can use an enum value as the index of an array, but that's not what you're doing in the code
> below.
No, you can't.
> Or, as a standard practice, include an extra identifier in the
> enumerator list to be used as the size (since the values are
> 0-based):
That feels like a bad way to me - it means that if you examine the
values of Months (which should be Month to fit into .NET naming
conventions) you'll find an extra value, and that the size of the
enumeration is 13 instead of 12.
Better (IMO) is to use something like:
static readonly int NumMonths = Enum.GetValues(typeof(Month)).Length;
(It's a shame enums aren't properly OO in .NET, but never mind.)
This gives the following code:
using System;
enum Month
{
January, February, March, April, May,
June, July, August, September, October,
November, December
}
class Test
{
static readonly int NumMonths = Enum.GetValues(typeof
(Month)).Length;
static void Main()
{
double[] income = new double[NumMonths];
// FAILS: income[Month.January] = 5.2;
income[(int)Month.January] = 5.2;
}
}
If you try to use the commented out line, you'll get the following
error:
Test.cs(18,16): error CS0266: Cannot implicitly convert type 'Month' to
'int'. An explicit conversion exists (are you missing a cast?)
Of course, if the OP is using .NET 2.0, he could use
Dictionary<Month,double> instead of an array to start with.
--
Jon Skeet - <(E-Mail Removed)>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too