简体   繁体   中英

C# compiler error in Visual Studio 2012, no longer error in VS2015

This is more of a curiosity question, since the fix is both easy and obvious. I use Visual Studio 2015 but my team mate uses Visual Studio 2012. We work on the same project. Yea yea, this is a bad idea but we'll fix this soon hopefully. Yesterday, I checked in some code which he integrated into his branch and immediately had compile errors. Here's the code (it has been simplified a bit since not all of it is necessary):

//Load basic project information from db
var projInfo = (from v in context.TPM_PROJECTVERSION
                join p in context.TPM_PROJECT on v.PROJECTID equals p.PROJECTID

                join pto in context.TPM_USER on v.TPM_USER1.USERID equals pto.USERID into primaryowner
                from subpto in primaryowner.DefaultIfEmpty()
                join pt in context.TPM_PROJECTTYPES on p.PROJECTTYPEID equals pt.PROJECTTYPEID
                where v.PROJECTID == projectId && v.VERSIONID == versionId
                select new
                {
                   ProjectName = v.NAME,
                   BusinessLaunchDate = p.BUSINESSLAUNCHDATE,
                   LearningExperiences = v.TPM_PROJECTVERSIONGAMEPLANS
                     .SelectMany(p => p.TPM_LEARNINGEXPERIENCES.Select(le => le.NAME)),
                }).First();

On my machine, this compiles and works fine. On his machine, he gets the error:

Error 10 A local variable named 'p' cannot be declared in this scope because it would give a different meaning to 'p', which is already used in a 'parent or current' scope to denote something else

The variable p in question is the p within the .SelectMany call:

.SelectMany(p => p.TPM_LEARNINGEXPERIENCES.Select(le => le.NAME)),

This apparently conflicts with the p defined in the above join:

join p in context.TPM_PROJECT on v.PROJECTID equals p.PROJECTID

To me, this seems fine. So I hide a variable in an outer scope I no longer need. I can fix his compile error by renaming one of the p variables.

My Question:

I know VS2012 uses C# 5.0, while VS2015 uses C# 6.0. Did 6.0 get more lenient on variable names in an inner scope, or is there some other setting that's coming into play here. Why is this an error on one and perfectly fine on another? BTW, I don't get any warnings either so it's not a Treat warnings as errors type of thing either.

Ideas?

AS a quick and save solution to avoid strange errors, Unify the building using c# 6 in both environment. You can install c# 6.0 into VS2012 on a per project basis as a NuGet package

Installing C# Compiler via Nuget

Install-Package Microsoft.Net.Compilers

Try this in a test environment and check if this error disappear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM