11

Is there a difference in the declaration of lambda expressions between the .NET Framework and .NET Core?

The following expressions compiles in .NET Core:

var lastShift = timeline.Appointments
                        .OfType<DriverShiftAppointment>()
                        .SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))
                        .OrderByDescending(x => x.Start)
                        .FirstOrDefault();

But not in the .NET framework.

The problem in this expression is the following part

.SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))

where x is declared twice (SelectMany and Where).

This is the error in the .NET Framework:

A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter

.NET framework

enter image description here

Reproducable example:

public class DemoClass
{
    public IList<int> Numbers { get; set; } = new List<int>();
}

class Program
{
    static void Main(string[] args)
    {
        var lst = new List<DemoClass>
        {
            new DemoClass
            {
                Numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 }
            },
            new DemoClass
            {
                Numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 }
            },
            new DemoClass
            {
                Numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 }
            }
        };

        var result = lst.SelectMany(x => x.Numbers.Where(x => x % 2 == 0))
                        .OrderByDescending(x => x);

        Console.WriteLine("Hello World!");
    }
}
BendEg
  • 20,098
  • 17
  • 57
  • 131

1 Answers1

10

It is telling you that problem is this line:

.SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))

Using the x twice confuses it, it is ambiguous, try this:

.SelectMany(x => x.Activities.Where(y => !y.IsTheoretical))

But you are right, it compiles in core but not framework. It looks to be like this: https://github.com/dotnet/roslyn/issues/38377. Reading that link, it looks like this is a change in C# 8.0, and core is targeting 8.0 while framework is targeting 7.2.

mikelegg
  • 1,197
  • 6
  • 10
  • That is totally clear and easy to solve, but not the problem. The problem is, why is it working under .net core? – BendEg Mar 24 '21 at 09:46
  • 2
    Probably differences in C# compiler. Anyway try to avoid this. – Svyatoslav Danyliv Mar 24 '21 at 09:49
  • @SvyatoslavDanyliv yes, it is already fixed, just seen this when using the same code in .net core and .net framework. – BendEg Mar 24 '21 at 09:49
  • @BendEg yes you are correct, I missed that point. I don't know why this is. – mikelegg Mar 24 '21 at 09:50
  • 4
    Nice find on the issue. It would be good if you could update your answer to say that this is a change introduced in C# 8, and not a .NET Core / .NET Framework difference – canton7 Mar 24 '21 at 10:44