How can I create a new instance of ImmutableDictionary?

前端 未结 5 1812
慢半拍i
慢半拍i 2020-12-15 15:18

I would like to write something like this:

var d = new ImmutableDictionary { { \"a\", 1 }, { \"b\", 2 } };

(using

5条回答
  •  心在旅途
    2020-12-15 15:46

    You can't create immutable collection with a collection initializer because the compiler translates them into a sequence of calls to the Add method. For example if you look at the IL code for var d = new Dictionary { { "a", 1 }, { "b", 2 } }; you'll get

    IL_0000: newobj instance void class [mscorlib]System.Collections.Generic.Dictionary`2::.ctor()
    IL_0005: dup
    IL_0006: ldstr "a"
    IL_000b: ldc.i4.1
    IL_000c: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2::Add(!0, !1)
    IL_0011: dup
    IL_0012: ldstr "b"
    IL_0017: ldc.i4.2
    IL_0018: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2::Add(!0, !1)
    

    Obviously this violates the concept of immutable collections.

    Both your own answer and Jon Skeet's are ways to deal with this.

    // lukasLansky's solution
    var d = new Dictionary { { "a", 1 }, { "b", 2 } }.ToImmutableDictionary();
    
    // Jon Skeet's solution
    var builder = ImmutableDictionary.CreateBuilder();
    builder.Add("a", 1);
    builder.Add("b", 2);   
    var result = builder.ToImmutable();
    

提交回复
热议问题