Compiler to check if keys in a dictionary are unique

I am looking for you to have errors to prevent assembly if there are duplicate keys in my static dictionary.

My current dictionary is below

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

But let's say someone accidentally swaps Sobeys for Nofrills, I would like a compiler error to be raised to prevent anything until this duplicate key is resolved. May I ask if this is possible? If so, how could I do this?

 public static readonly Dictionary<string, string> Fruits = new Dictionary<string, string> { {"NoFrills", "Apples"}, {"NoFrills", "Oranges"} } 
+5
source share
4 answers

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 only have valid identifiers as keys in the dictionary.

How is the ToDictionary method ToDictionary : In C # convert an anonymous type to an array of keys / values?

+6
source

No, it's runtime. As soon as the class is loaded into memory, it will throw an exception (which is essentially runtime).

You can add a custom check through the diagnostic analyzer, but it will be very painful for a very small gain. I suggest that you just leave it as it is and keep track of any exceptions for a new deployment. You can always add a comment to make it clear to other developers that the keys must be unique, but where did you stay? It is assumed that the developer must know the basic rules of the structure.

You can also use, for example, an enumeration as a key, which will clear it in devtime when you try to add something that already exists. Another option is to refer to const string fields, although it remains somewhat fragile.

+8
source

The C # compiler does not provide this feature. You will get an exception at runtime.

To solve this problem, you must run your own preprocessing checks or handle runtime exceptions.

+1
source

I would like a compiler error to be raised

It's not a mistake. Therefore, the compiler does not issue a compile-time error. The collection initializer is syntactic sugar and is converted to the corresponding Add() call (or the indexer in the case of alternative syntax).

Your best bet is to rely on some third-party code analysis tool that can detect such potential errors.

+1
source

All Articles