0

Say I have a giant list of definitions that are used to lookup values that an object can default to given a "type number". This type number is unique, and points to data that the object will be set to when initialized with it.

My usual go-to is to have a static property that will return a new Dictionary with each get. E.g.

public static Dictionary<long, Tuple<string,DefaultValue>> Defaults
{
   get { return new Dictionary<long, DefaultValue>() 
         {
            { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
            { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
            ... 
         }
   }
}

This works, and the lookup list will likely never be large enough for this to noticeably impact performance or memory usage, but being somewhat stingy on performance I don't like the idea of having a new Dictionary instantiated every time it is referenced. I would much rather it be completely hard-coded into memory.

How would this be solved in a professional way? I feel like the way I am doing it above is incredibly sloppy.

Servy
  • 202,030
  • 26
  • 332
  • 449
w0f
  • 908
  • 9
  • 23

2 Answers2

4

You can use an auto-property initializer or set the value in the static constructor. The latter is shown below.

static MyClass()
{
   Defaults = new Dictionary<long, DefaultValue>(){
        { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
        { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
      };
}

public static Dictionary<long, DefaultValue> Defaults {get; private set;}

Example with Auto-property initializer (no static constructor is needed and the private set is omitted as the assumption can now be made you are using a c# version that supports that).

public static Dictionary<long, DefaultValue> Defaults {get;} = new Dictionary<long, DefaultValue>(){
        { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
        { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
      };

Side note: If the values should not be altered you could also expose the IReadonlyDictionary interface on the property.

Igor
  • 60,821
  • 10
  • 100
  • 175
0

If the lookup table is small and your goal is to increase the performance of the lookup operation then you can also consider using a function with a switch statement instead of a lookup dictionary.

See this answer for more information: https://stackoverflow.com/a/11617459/1709981

tony
  • 1,274
  • 1
  • 11
  • 27