Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler to check if keys in dictionary are Unique

Tags:

c#

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"}
}
like image 676
Master Avatar asked Aug 24 '16 20:08

Master


2 Answers

Nope, that's a runtime thing. As soon as the class is loaded into memory it will throw an exception (which are inherently runtime).

You could add a custom check through a diagnostic analyzer but that would be a lot of pain for very little gain. I suggest you just keep it as it is and keep an eye on any exceptions with a new deployment. You can always add a comment to make it clear to other devs that keys have to be unique but where do you stop? A developer is supposed to know basic framework rules like that.

You could also use, for example, an enum as the key which would make it clear at devtime when you try to add something that already exists. Another option is to refer to const string fields although it remains somewhat brittle.

like image 104
Jeroen Vannevel Avatar answered Sep 22 '22 01:09

Jeroen Vannevel


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?

like image 43
just.ru Avatar answered Sep 18 '22 01:09

just.ru