Creating a script with List

Viewed 235

I'm attempting to create a script with Microsoft.CodeAnalysis.CSharp.Scripting. As soon as I add List<> the code errors. I thought I had all the necessary references and usings included, however it still errors stating The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?

These are my usings in the code

using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics;

Below is my example unit test

[TestMethod]
public void RunGenericListTest()
{
    var code = @"
List<string> strings = new List<string>();
strings.Add(""test string"");            
return output;";

    var options = ScriptOptions.Default;

    options.WithReferences(typeof(System.Collections.CollectionBase).Assembly);
    options.WithReferences(typeof(System.Collections.Generic.List<>).Assembly);
    options.WithImports("System.Collections");
    options.WithImports("System.Collections.Generic");

    var result = CSharpScript.RunAsync(code, options).Result;

    Debug.WriteLine(result);
}

This errors on the CSharpScript.RunAsync every time. Can someone enlighten me on what I'm missing?

1 Answers

I think the issue is, WithImports does not mutate options but rather returns a copy

var code = @"
List<string> strings = new List<string>();
strings.Add(""test string"");            
return strings;";

    var options = ScriptOptions.Default
                .WithImports("System.Collections.Generic"); // chaining methods would work better here.
    // alternatively reassign the variable:
    // options = options.WithImports("System.Collections.Generic");

    var result = CSharpScript.RunAsync(code, options).Result;

    Debug.WriteLine((result.ReturnValue as List<string>).First());
Related