Max Toro
Max Toro

Reputation: 28608

Can IL produced by C# 4.0 compiler run on CLR 2.0?

Can IL produced by C# 4.0 compiler run on CLR 2.0?

To clarify, I'm not asking about VS 2010 multi-targeting (where VS chooses the right compiler version), I want to know if csc.exe 4.0 supports multi-targeting...

Upvotes: 6

Views: 1187

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062915

If all else fails, try it. I've just tested the following in VS2010b2, compiled targeting 2.0:

using System;    
class Program {
    static void Main() {
        Write();
        Write(msg: "world");
        Console.ReadLine();
    }
    static void Write(string msg = "Hello") {
        Console.WriteLine(msg);
    }
}

This uses two new C# 4.0 language features, which use the meta-data that is also present in .NET 2.x/3.x/CLR 2; it executes fine on my regular (CLR 2) machine (my VS2010b2 is a VM). So I conclude "yes, for some features". Obviously if you use a framework-dependent feature (dynamic, etc) it isn't going to end so well.

Edit: re your comment; I've tried csc at the command-line, and by default this does target CLR 4; I'll try to see if I can get it to target CLR 2 (like VS obviously can). Unfortunately, it no longer includes the (faked, btw) command line in the build output window...

Update: some "in the know" people came back with:

Pass /nostdlib and a reference to the 2.0 mscorlib.dll.

And sure enough:

C:\Windows\Microsoft.NET\Framework\v4.0.21006>csc /nostdlib /reference:%SystemRo
ot%\microsoft.net\framework\v2.0.50727\mscorlib.dll /out:c:\my.exe /target:exe "
C:\Users\Marc\Documents\Visual Studio 2010\Projects\ConsoleApplication6\ConsoleA
pplication6\program.cs"
Microsoft (R) Visual C# 2010 Compiler version 4.0.21006.1
Copyright (C) Microsoft Corporation. All rights reserved.

works fine (exe works on my non-4.0 machine). Credit: Kevin Pilch-Bisson

Upvotes: 7

Bevan
Bevan

Reputation: 44307

It depends on the compiler.

Indications so far seem to indicate that the C# 4.0 compiler will be able to target the .NET 2.0 runtime, generating IL that is compatible with that runtime and ensuring that you only reference assemblies that also run on .NET 2.0.

Note that targeting is a choice, though - and there's no guarantee that any other compiler will have the same feature.

Mostly, I guess that it's a decision that will be made by the team implementing the compiler.

For example, it's likely that the C# and VB.NET compiler teams will support multitargeting (though they might back off from that and leave it as a Visual Studio feature, where VS chooses different compilers for different targets).

Other vendors using the .NET framework may make other decisions.

Upvotes: 1

Bob
Bob

Reputation: 99754

C# 4.0 uses the .NET CLR 4.0 so there will be no binary compatibility with the CLR 2.0. You will be able to target the 2.0 framework though.

Upvotes: 1

Related Questions