Reputation: 3361
I've lost several days trying to debug an issue that boils down to this:
Properties of type IImmutableDictionary
can appear to be initialized in code but actually remain empty.
Example class
public class TestClass
{
public IDictionary<string, string> DictProp { get; set; } = new Dictionary<string, string>();
public IImmutableDictionary<string, string> ImmutDictProp { get; set; } =
ImmutableSortedDictionary<string, string>.Empty;
}
Illustration code
var bad = new TestClass
{
// This works fine
DictProp =
{
{"uno", "one"},
{"due", "two"}
},
// This does NOT initialize the field, and compiler is happy
ImmutDictProp =
{
{ "uno", "one" },
{ "due", "two" }
}
};
Trace.Assert(bad.DictProp.Count == 2);
Trace.Assert(bad.ImmutDictProp.Count == 0); // <<<< expecting 2 elements
var good = new TestClass
{
ImmutDictProp = new Dictionary<string, string>
{
{ "uno", "one" },
{ "due", "two" }
}.ToImmutableSortedDictionary()
};
Trace.Assert(good.ImmutDictProp.Count == 2);
Contrary to some comments, this question is more than mere Immutable Dictionary instantiation. I'm asking about the initialization of a property and the absence of a compiler error. I'll provide an answer summarizing what I've learned.
Upvotes: 0
Views: 56