I have an Enum
enum Product{
Knife,
Fork,
Spoon
}
and a Dictionary with one entry per Enum member:
var productPrices = new Dictionary<Product, double>(){
{Product.Knife, 10},
{Product.Fork, 10},
{Product.Spoon, 15}
}
The Dictionary is supposed to contain the price for every product. At one point I loop through all products and get their prices
foreach(Product p in Enum.GetValues(typeof(Product))){
var price = productPrices[p];
}
and this will of course throw an error if some product is not found in the Dictionary.
Is this a case of bad design, as the Dictionary is tightly coupled to the Enum, even though there is not formally any connection between the two? If, for example, someone was to add a new member to the Enum, they would need to be aware that they also would have to add a new entry to the Dictionary.
If it is a bad design choice, what is a better alternative?
When you use a strongly typed language like
C#, it is better to create an object(struct, class, record)for this scenario, and usingDictionaryis not a good option.