R
Richard Drysdall
Hi.
In C/C++, I'm used to using a table-driven approach for some problems to
avoid large case statements. For example (off the top of my head, may
contain syntax errors and error checking excluded):
typedef struct
{
const char *name;
unsigned int id;
} ANIMALMAPPING;
static ANIMALMAPPING animalIdMapping [] =
{
{"frog", 174},
{"cow", 206},
{"bird", 92}
};
int GetAnimalIdFromName (const char *animalName)
{
for (int animal = 0; animal < ARRAYSIZE (animalIdMapping); animal++)
if (stricmp (animalName, animalIdMapping [animal].name) == 0)
etc...
}
In C#, I seem to have trouble defining the animalIdMapping array - I've got:
private AnimalEffectMapping [] animalEffectMapping
= new AnimalEffectMapping [3]
{
{"frog", 174},
{"cow", 206},
{"bird", 92}
};
but I get the following compile error:
error CS0623: Array initializers can only be used in a variable or field
initializer. Try using a new expression instead.
But when I try putting 'new AnimalEffectMapping' in front of each line
in the table, the compiler thinks I'm trying to make an array out of
each line.
What do I need to change to get this working, and does C#/.Net offer a
better approach to solving this kind of problem than table-driven code?
Thanks.
In C/C++, I'm used to using a table-driven approach for some problems to
avoid large case statements. For example (off the top of my head, may
contain syntax errors and error checking excluded):
typedef struct
{
const char *name;
unsigned int id;
} ANIMALMAPPING;
static ANIMALMAPPING animalIdMapping [] =
{
{"frog", 174},
{"cow", 206},
{"bird", 92}
};
int GetAnimalIdFromName (const char *animalName)
{
for (int animal = 0; animal < ARRAYSIZE (animalIdMapping); animal++)
if (stricmp (animalName, animalIdMapping [animal].name) == 0)
etc...
}
In C#, I seem to have trouble defining the animalIdMapping array - I've got:
private AnimalEffectMapping [] animalEffectMapping
= new AnimalEffectMapping [3]
{
{"frog", 174},
{"cow", 206},
{"bird", 92}
};
but I get the following compile error:
error CS0623: Array initializers can only be used in a variable or field
initializer. Try using a new expression instead.
But when I try putting 'new AnimalEffectMapping' in front of each line
in the table, the compiler thinks I'm trying to make an array out of
each line.
What do I need to change to get this working, and does C#/.Net offer a
better approach to solving this kind of problem than table-driven code?
Thanks.