Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compile C# with Specific Language Version

Tags:

c#

csc

Let's say I want to demo to someone about the differences between foreach in C# 4.0 and 5.0.

So I write up my code snippet:

public static void Main() {     string[] fruits = { "Apple", "Banana", "Cantelope" };     var actions = new List<Action>();     foreach (var fruit in fruits)     {         actions.Add(() => Console.WriteLine(fruit));     }      foreach(var a in actions)     {         a();     }    } 

But no matter how I compile it, it always works as it does in 5.0*. I've tried setting the language version in the csproj file (Build -> Advanced -> Language Version) and I've tried just building it on the command line:

csc myProgram.cs /langversion:4 

I can't get it to work the "old" way. Any help? Bonus points if you can tell me how to do it on both the command line and Visual Studio.

* For anyone who doesn't know, in C#. <= 4.0 this would print Cantelope Cantelope Cantelope, while in C# 5.0+ it would (more intuitively) print Apple Banana Cantelope. Here's a link, and here's another.

like image 400
Pharylon Avatar asked Apr 06 '15 17:04

Pharylon


People also ask

What is the command to compile in C?

Run the gcc command to compile your C program. The syntax you'll use is gcc filename. c -o filename.exe . This compiles the program and makes it executable.

How do I compile a C file in Windows?

Type "cl filename. c" (without quotes) and press the "Enter" key to compile the code page. The C file is compiled into an executable (EXE) file named "filename.exe."

How does C compile work?

The compiler checks the source code for the syntactical or structural errors, and if the source code is error-free, then it generates the object code. The c compilation process converts the source code taken as input into the object code or machine code.


1 Answers

The purpose of the /langversion is only to make the compiler accept specific language constructs. It does not affect the actual behaviour of the compiler.

The documentation states that:

Causes the compiler to accept only syntax that is included in the chosen C# language specification.

and

Because each version of the C# compiler contains extensions to the language specification, /langversion does not give you the equivalent functionality of an earlier version of the compiler.

So to demonstrate the different behaviour, you will have to use a different csc.exe, installed with the right framework versions.

C:\Windows\Microsoft.NET\Framework\v3.5>csc /out:c:\temp\foo-35.exe c:\temp\foo.cs Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.7903 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved.   C:\Windows\Microsoft.NET\Framework\v3.5>c:\temp\foo-35.exe Cantelope Cantelope Cantelope 
like image 63
Anders Abel Avatar answered Sep 19 '22 09:09

Anders Abel