Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reference to System.Collections for CSharpCompilation

I need to use Dictionary<string, string> in my dynamic code.

So I try to get a reference to the assembly comprising the type with the following code:

MetadataReference.CreateFromFile(typeof(Dictionary<,>).Assembly.Location)

But this return the following location:

C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.6\System.Private.CoreLib.dll

And the compilation fails with

CS0012: The type 'Dictionary<,>' is defined in an assembly that is not referenced. You must add a reference to the assembly 'System.Collections, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

I solve the problem with the following code:

MetadataReference.CreateFromFile(
    System.IO.Path.Combine(
        System.IO.Path.GetDirectoryName(typeof(Dictionary<,>).Assembly.Location),
        "System.Collections.dll"))

Is there a more permanent way to load the good assembly for Dictionary<,> ?

like image 918
tschmit007 Avatar asked Sep 06 '25 22:09

tschmit007


1 Answers

I recently got the same problem with .net 6 (C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.8\System.Private.CoreLib.dll) I was able to compile my dynamic code by CSharpCompilation - simply you should add using statement into your dynamic code:

using System.Collections.Generic;
like image 117
Evgeny Ukladchikov Avatar answered Sep 10 '25 17:09

Evgeny Ukladchikov