Peter L
Peter L

Reputation: 3361

Immutable dictionary property initialization in C#

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.

  1. Why is the compiler allowing this? (I'm using .NET 6.0.417 on Linux)
  2. Should I stay away from this type of dictionary initialization?

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

Answers (0)

Related Questions