29

So we've finally got VS2010 on some developer stations at work and can use the C# 4.0 features. Although most of what we develop will still have to target .Net 3.5 for the time being.

When I start a new project and set the target to .Net 3.5, it still allows me to use C# 4.0 such as dynamic. Can you therefore use C#4.0 features whilst targetting .net 3.5 and will these features work in environments where .Net 4.0 is not available?

Thanks.

Darren Young
  • 10,972
  • 36
  • 91
  • 150
  • Ya, this is weird. I noticed that on our app as well and ours is 2.0. I'd be interested in what the answers would be. – Jon Jun 02 '11 at 13:53

1 Answers1

44

dynamic code will not compile if you target the .NET 3.5 framework.

To be more clear, the compiler will allow you to define and assign a dynamic variable, such as:

dynamic x = 3;

That one line of code will compile, because dynamic just compiles to object as far as types are concerned. But if you then try to do anything with that variable, as in:

Console.WriteLine(x);

... then the compiler would have to generate code to discover/coerce the real type, which it cannot do; you'll get the following compile errors:

  1. Predefined type 'Microsoft.CSharp.RuntimeBinder.Binder' is not defined or imported
  2. One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

The C# 4 compiler relies on the DLR and specifically the Microsoft.CSharp assembly for everything related to dynamic. These aren't available in .NET 3.5. So the answer is no, you cannot use dynamic when targeting Framework version 3.5.

Aaronaught
  • 120,909
  • 25
  • 266
  • 342
  • 1
    I often wondered what the difference was. Thank you Aaronaught – Gustavo Mori Jun 02 '11 at 18:02
  • Reading that error makes me wonder, so what happens if you included the those 2 dlls as copy local, would that be enough? Or would it never find those dlls for picking the GAC version of the older framework always? – Chris Marisic Jun 02 '11 at 18:06
  • 1
    @Chris: Microsoft.CSharp doesn't actually *contain* the DLR; the DLR is part of the framework itself. So no, including that DLL won't help you; even if you do get it to compile, it won't actually run. – Aaronaught Jun 02 '11 at 22:24
  • 5
    +1 Another solution if you googled the 2 error messages that Aaronaught lists, is to just add a Reference to Microsoft.CSharp 4.0 – Jeremy Thompson Mar 21 '12 at 22:28
  • Jeremy - you can't reference Microsoft.CSharp 4.0 from .NET 3.5 I don't think? – NickG Apr 17 '13 at 09:38