Piotr Zierhoffer
Piotr Zierhoffer

Reputation: 5151

How can I compile C#7 code on the fly?

I have a simple code that I try to compile on the fly:

namespace A
{
    class Test
    {
        public static void Test()
        {                
            int.TryParse("12", out int result);
        }
    }
}

Normally I use CSharpCodeProvider or CodeDomProvider. Unfortunately, with transition to C#6/C#7, I get the following error:

error CS1644: Feature `declaration expression' cannot be used because it is not part of the C# 6.0 language specification

Of course the whole code does contain C#7 features and they compile just fine, using msbuild/xbuild.

I understand the error, but I don't know if there is any other way to compile this code?

Important notice - I run it on Mono, but I do not have an option to try .Net right now. It might be a Mono issue, but it does seem to be generic.

Upvotes: 4

Views: 671

Answers (1)

svick
svick

Reputation: 244797

The error message seems to indicate that the version of the compiler you're using understands declaration expressions, but has been set to not allow them.

This is the case for the version of CodeDOM that's included in the latest version of Mono that's included in Ubuntu 16.04 (Mono 4.2.1). In that version, you can allow declaration expressions by setting /langversion:experimental.

In CodeDOM, you do that by setting CompilerParameters.CompilerOptions, for example:

compiler.CompileAssemblyFromSource(
    new CompilerParameters { CompilerOptions = "/langversion:experimental" }, code);

With this code, your source compiles for me on Mono 4.2.1. But since it's an experimental feature in this version of the compiler, it might not work perfectly.

It's possible that upgrading your version of Mono could help.

I believe /langversion:experimental is specific to Mono, so this code likely won't work on other implementations of .Net.

Upvotes: 4

Related Questions