Superbest
Superbest

Reputation: 26602

Can I initialize Dictionary Values automatically?

Let's say I want to store my data as a bunch of named lists.

I really like how with Dictionary, you can do:

myDictionary["SomeKey"] = new List<string>{ "SomeString" };

But unfortunately, I cannot safely do:

myDictionary["SomeKey"].Add("SomeString");

Because if the List at SomeKey has not yet been initialized, I'll get a null reference exception.

So everytime I alter a value in the dictionary, I have to do:

if (!myDictionary.ContainsKey("SomeKey")) myDictionary["SomeKey"] = new List<string>();

Before I can safely add to each list. It looks ugly and distracts from non-boilerplate code. I also duplicate code in several places (accessing SomeKey several times when all I want to say is "add this element to the list at SomeKey, regardless of whether it is empty or not").

There is basically no reason why I would want uninitialized values in my Dictionary. If it was an array of List, I would have looped through every element beforehand and initialized each member; I can't do this with Dictionary because I don't know what the keys will be in advance.

Is there a more concise syntax for saying, "access the value at this key, and if it is null, then initialize it"?

Upvotes: 2

Views: 1553

Answers (1)

Paul
Paul

Reputation: 36319

I don't think there is, but you could do it as an extension method if you wanted. Something like

public static class DictionaryExtensions
{
    public static SafeAdd(this Dictionary<string,List<string>> obj, string key, string val)
    {
        // your example code
    }
}

then you could do myDictionary.SafeAdd("somekey","somestring");

Upvotes: 3

Related Questions