Search code examples
c#visual-studio-2019read-eval-print-loopimmutable-collections

Is it possible to use Immutable.Collections on C# Interactive?


I am using the C# Interactive window (i.e. the REPL) on Visual Studio 2019, with latest updates. I want to use immutable collections but can't get them to work. (I have no problem using them in a compiled C# project).

Strangely, if I enter (into C# Interactive window):

using System.Collections.Immutable;

C# Interactive accepts this, implying that it can see the namespace. But if I then try to use it e.g.:

var a = ImmutableList.Create<int>(1,2,3);

I get the error message: 'The name 'ImmutableList' does not exist in the current context.' It makes no difference if I fully-qualify the name of ImmutableList.

Possibly I am not understanding which version of .NET C# Interactive is working against. I understand that Immutable.Collections are now native within .NET Core 3, but maybe C# Interactive doesn't use this version? (How can you tell/specify the .NET version in C# Interactive?). Even so, it seems odd that it does not protest at the using directive.


Solution

  • You need to reference the System.Collections.Immutable assembly first. To do that, use this:

    #r "System.Collections.Immutable.dll"
    

    Now you can use the object in the System.Collections.Immutable namespace.