Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compile for .NET 2.0 with C# 6.0?

Visual Studio 2015 has no problem compiling for the older CLR with new c# compiler. It seems that it uses VBCSCompiler.exe for this under the hood, but I cannot find any documentation about VBCSCompiler.exe command line options.

On the other hand csc.exe does not seem to have an option to select target CLR. You can use the latest csc.exe which will compile for CLR 4, or you can use an older csc.exe to compile for CLR 2, but then it won't be C# 6.

So how do I compile for CLR 2 and c# 6.0? Do I have to have visual studio for this? Are there any other options?

like image 380
Andrew Savinykh Avatar asked Oct 27 '25 07:10

Andrew Savinykh


1 Answers

You can specify old .NET assemblies with /r:

 /reference:<alias>=<file>     Reference metadata from the specified assembly
                               file using the given alias (Short form: /r)
 /reference:<file list>        Reference metadata from the specified assembly
                               files (Short form: /r)

You will also need to suppress the automatic inclusion of the modern mscorlib with /nostdlib:

 /nostdlib[+|-]                Do not reference standard library (mscorlib.dll)

Together, these make it so that you can build .NET 2.0 apps with the C# 6 compiler.

csc.exe /r:"C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll" /nostdlib Program.cs

You can even use C# 6 features in your app! (as long as they are compiler-only features that don't involve the .NET runtime)

public static string MyProp { get; } = "Hello!";
static void Main(string[] args)
{
    Console.WriteLine(MyProp);
    // prints "Hello!"

    var assembly = Assembly.GetAssembly(typeof(Program));
    Console.WriteLine(assembly.ImageRuntimeVersion);
    // prints "v2.0.50727"
}
like image 191
Tim S. Avatar answered Oct 29 '25 21:10

Tim S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!