Error compiling C# 6 with Microsoft.Build ( Visual Studio SDK )

6.6k Views Asked by At

This is a working C#6 test code. It compiles on VS2015

namespace testcode
{
    class Program
    {
        static void Main(string[] args)
        {
            string x = null ;
            string y = x?.Substring(0, 2);
            return;
        }       
    }
}

The cproj has toolsversion 14.0

<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

This is how I'm trying to compile it with MSBUILD via the Visual Studio SDK

//References Microsoft.Build and Microsoft.Build.Framework
namespace MSBuildTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var pc = new Microsoft.Build.Evaluation.ProjectCollection(Microsoft.Build.Evaluation.ToolsetDefinitionLocations.Registry);
            pc.DefaultToolsVersion = "14.0";
            pc.RegisterLogger(new Microsoft.Build.Logging.ConsoleLogger(Microsoft.Build.Framework.LoggerVerbosity.Detailed));
            var pr = pc.LoadProject(@"C:\path\to\testcode.cproj");
            pr.Build();
        }
    }
}

This is the error message

Program.cs(8,26): error CS1525: Invalid expression term '.'
Program.cs(8,27): error CS1003: Syntax error, ':' expected
    0 Warning(s)
    2 Error(s)

I guess it's using the wrong MSBUILD executable, but I found no way to force the MSBUILD bin path.

2

There are 2 best solutions below

0
On BEST ANSWER

You are referencing the older version of the Microsoft.Build.* libraries, make sure you are pointing at the right ones. If you use old ones you will be trying to build with C# v5 which doesn't understand the null propogation operators.

For example, on my build machine they are:

C:\Program Files (x86)\MSBuild\14.0\Bin\Microsoft.Build.dll

and

C:\Program Files (x86)\MSBuild\14.0\Bin\Microsoft.Build.Framework.dll

2
On

To Resolve this issue, Try below setting:

For anyone else that gets this error, don't use the msbuild located at: C:\Windows\Microsoft.NET\Framework64\v4.0.30319

Instead use the msbuild at: C:\Program Files (x86)\MSBuild\14.0\Bin