Equivalent to table-driven code

  • Thread starter Thread starter Richard Drysdall
  • Start date Start date
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.
 
Richard Drysdall said:
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.

You need to change each of the lines inside the array to something
like:

new AnimalEffectMapping ("frog", 174),

Note the round brackets instead of braces. You're calling a constructor
- there's no equivalent of the sort of "automatic" struct
initialization in C.
 
Jon said:
Richard Drysdall said:
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.

You need to change each of the lines inside the array to something
like:

new AnimalEffectMapping ("frog", 174),

Note the round brackets instead of braces. You're calling a constructor
- there's no equivalent of the sort of "automatic" struct
initialization in C.

Additionally, you might to look into the HashTable or Dictionary<>
classes, that offer far quicker searching than looping through all the
elements.
 
Back
Top