4

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
  • Fair play for including a unit test. It's nice to see questions with minimal, reproducible examples. Commented Nov 20, 2020 at 10:26

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

2 Comments

So its a syntax error. I didn't realise that the options wasn't being added to if you didn't reassign it to itself. The returns a copy link was a little difficult to understand initially but was also helpful. Thanks
@Thundter I'm sorry I couldn't find this class in the documentation. Had to go to the source

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.