A shortcut I often use in C when dealing with embedded APIs (communications protocols, primarily) allows me to edit an enum array and have everything else sized correctly after that:
typedef enum {
errortype1,
errortype2,
...
errortypeN,
ERROR_TYPE_MAX
} ErrorTypeList;
int errorcounts[ERROR_TYPE_MAX]; // Create array to hold a counter for each error type
As long as I add new error types before ERROR_TYPE_MAX then I can use that value everywhere else to give me the size of the enum.
In C#, however, this doesn’t work as-is:
enum ErrorTypeList {
errortype1,
errortype2,
...
errortypeN,
ERROR_TYPE_MAX
};
int errorcounts[ErrorTypeList.ERROR_TYPE_MAX]; // Create array to hold a counter for each error type
This usage presents the error Array size cannot be specified in a variable declaration which suggests using new.
Is defining the array at runtime (via new) my only option, or is there a way to accomplish this without a new, since the size of the enum isn’t going to change after compilation?
Is there an alternative to this type of enum sizing pattern that better fits into c#?
You will have to use
new.A variable/field declaration does not specify the size of the array, that’s only accomplished when you construct the array instance.
At most you can specify how many dimensions the array will have, but not the size of each dimension.