Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of a lambda variable in C#?

Tags:

scope

c#

lambda

I'm confused about the scope of the lambda variable, take for instance the following

var query =      from customer in clist     from order in olist     .Where(o => o.CustomerID == customer.CustomerID && o.OrderDate ==  // line 1         olist.Where(o1 => o1.CustomerID == customer.CustomerID)        // line 2              .Max(o1 => o1.OrderDate)                                  // line 3     )     select new {         customer.CustomerID,         customer.Name,         customer.Address,         order.Product,         order.OrderDate     }; 

In line 1 I have declare a lambda variable 'o' which means I cannot declare it again in line 2 (or at least the compiler complains if I try to) But it doesn't complain about line 3 even though 'o1' already exists??

What is the scope of a lambda variable?

like image 843
mfc Avatar asked May 08 '12 07:05

mfc


People also ask

What is the scope of a lambda?

1 Scope of a Lambda Expression. The body of a lambda expression has the same scope as a nested block. The same rules for name conflicts and shadowing apply. It is illegal to declare a parameter or a local variable in the lambda that has the same name as a local variable.

What is the scope of a lambda function C++?

The context of a lambda is the set of objects that are in scope when the lambda is called. The context objects may be captured then used as part of the lambda's processing. Capturing an object by name makes a lambda-local copy of the object. Capturing an object by reference allows the lambda to manipulate its context.

How are lambda expressions scoped?

In lambda expressions, this and super keywords are lexically scoped means that this keyword refers to the object of the enclosing type and the super keyword refers to the enclosing superclass. In the case of an anonymous class, they are relative to the anonymous class itself.

What is lambda in C?

Lambda Function − Lambda are functions is an inline function that doesn't require any implementation outside the scope of the main program. Lambda Functions can also be used as a value by the variable to store. Lambda can be referred to as an object that can be called by the function (called functors).


1 Answers

The brackets give the clue - the lambda variable is captured in the scope of where it's declared:

.Where(o => ... olist.Where(o1 => ...).Max(o1 => ...))   //  |----------------------------------------------| scope of o   //                       |---------|                 scope of first o1   //                                      |---------|  scope of second o1 

Note that there's no overlap for the two o1 variables, but they both overlap (or shadow) the o variable and hence can't use the same name.

like image 164
yamen Avatar answered Sep 18 '22 13:09

yamen