Changing the C# language version used in your projects from within Visual Studio

Posted: (EET/GMT+2)

 

Now that Visual Studio 2015 is available and the C# language version 6 can easily be used, I wanted to share a tip about checking and changing your compiler version option from within Visual Studio.

To check the C# language version you are using, open up your project's properties, go to the Build tab, and click the Advanced button on the lower-right corner. The dialog box titled "Advanced Build Settings" opens, and at the top of this dialog box, you have the setting "Language Version".

The setting you set here corresponds to this setting in your .csproj project file. For example:

<LangVersion>6</LangVersion>

If the setting is "default", then the latest language version is used, and no setting is set in the project file. To quickly detect which language version you are using (probably whether you are getting new C# 6 features or not), you can simply try using one of the new features in code.

For example, the new Null-Conditional Operator is very useful in checking for null values. Try this code:

string input = "abc  ";
string trimmed = input?.Trim();

In C# 6, the above code will not fail (throw an exception) if "input" happens to be null. Instead, it simply returns the null value, so that "trimmed" would be null, too.

If you tried to compile the above code with C# 6 features disabled, you will get the following error message:

Error CS8026: Feature 'null propagating operator' is not
available in C# 5. Please use language version 6 or greater.

Note that this feature to enable C# 6 does not require you to use the latest compiler features, as in the Microsoft.CodeDom.Providers.DotNetCompilerPlatform NuGet package. Thus, you can use C# 6 features, with or without the "Roslyn" engine.

Speaking of different compilers, if you instead prefer to build your code from the command-line using CSC, the csc.exe compiler accepts the "/langversion" option. This is the same option you can give through your project's properties in Visual Studio.

Hope this helps!