0

I'm trying to include an extension methods static class in a dynamically generated assembly, except that i keep getting a compiler error of 'Type expected' at line 6, column 28, which happens to be on the word 'this'. If i remove 'this' no error is returned (but then it is not an extension method).

 public static void CodeDomDooDad()
    {
        using (var provider = new CSharpCodeProvider())
        {
            var compilerParameters = new CompilerParameters();

            compilerParameters.ReferencedAssemblies.Add("system.dll");
            compilerParameters.CompilerOptions = "/t:library";
            compilerParameters.GenerateInMemory = true;

            var sb = new StringBuilder();

            sb.Append("namespace MooCow \n{ \n");
            sb.Append("public static class Extensions {\n");
            sb.Append("public static string ToMoo(this string s) {\n");
            sb.Append("return s.Replace(\" \",\"moo\");\n");
            sb.Append("}\n");
            sb.Append("}\n");
            sb.Append("}\n");

            //Console.WriteLine(sb.ToString());

            var cr = provider.CompileAssemblyFromSource(compilerParameters, sb.ToString());
            if (cr.Errors.Count > 0)
            {
                CompilerError error = cr.Errors[0];
                Console.WriteLine(
                    "error:"+error.ErrorText + 
                    " line:" +error.Line + 
                    " col:" +error.Column + 
                    " isWarning:" + error.IsWarning);
            }
        }
    }

This is the generated code, which works fine.

namespace MooCow {
public static class Extensions
{
    public static string ToMoo(this string s)
    {
        return s.Replace(" ", "moo");
    }
}

}

brianc
  • 1,547
  • 3
  • 16
  • 30

1 Answers1

0

i think i found out, had to add CompilerVersion to CSharpProvider constructor... var provider = new CSharpCodeProvider( new Dictionary() { { "CompilerVersion", "v3.5" }})

brianc
  • 1,547
  • 3
  • 16
  • 30
  • Did you find that the framework version was not being pulled in from the machine.config? It was my understanding that without the constructor that is where the compiler version was grabbed from. – webworm Feb 16 '18 at 22:43
  • @webworm I honestly can't remember :/ – brianc Feb 17 '18 at 19:06