Search code examples
c#dictionarystandards

C# Enforcing Use of Dictionary Keys


I'm wondering what best practice is for verifying or enforcing the Keys used for a Dictionary object/parameter.

Take for example this method:

public override SqlServerQueryBuilder From(Dictionary<string, string> tableReferenceDictionary)
        {

            this.SelectQuery += " FROM " + this.IdentifierStart + tableReferenceDictionary["Database"] + this.IdentifierEnd
                             + "." + this.IdentifierStart + tableReferenceDictionary["Schema"] + this.IdentifierEnd
                             + "." + this.IdentifierStart + tableReferenceDictionary["Table"] + this.IdentifierEnd;

            return this;
        }

This method takes a Dictionary parameter, and makes an assumption about the keys used. If the caller passes a typo ("database" instead of "Database") then this code will throw an exception. Is there a better way to manage this?

Maybe a different data type that achieves the same thing?

Maybe use a enum and make the key of type enum (Dictionary<enum, string>)?


Solution

  • A custom class here is more appropriate, so you can enforce all your "keys" (which will be properties in the new class) are filled as expected.