Master Master - 3 months ago 11
C# Question

Compiler to check if keys in dictionary are Unique

I'm looking to have a error raise to prevent a build if there are duplicate keys in my static Dictionary.

My current Dictionary below

public static readonly Dictionary<string, string> Fruits = new Dictionary<string, string>
{
{"Sobeys", "Apples"},
{"NoFrills", "Oranges"}
}


But lets say someone accidentally changes Sobeys to be Nofrills, I would like a compiler error to be raised to prevent anything to be done until that duplicate key is resolved. May I ask is that possible? If so how abouts would I do that?

public static readonly Dictionary<string, string> Fruits = new Dictionary<string, string>
{
{"NoFrills", "Apples"},
{"NoFrills", "Oranges"}
}

Answer

You can also use the following hack (I do not recommend it): convert anonymous type to dictionary. Anonymous types do not allow duplicate property names.

Example:

Dictionary<string, string> Fruits = ToDictionary(
   new
   {
      Sobeys = "Apples",
      NoFrills = "Oranges"
   }
);

But this approach has the following limitation: you can have only valid identifiers as keys in your dictionary.

How to implement ToDictionary method is described there: In c# convert anonymous type into key/value array?