472,985 Members | 2,540 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,985 software developers and data experts.

Captured variables

var result = new List<StockLevelRow>();
foreach(SomeClass c in SomeList)
result.Add(
new StockLevelRow(c.Name,
delegate() { return c.StockLevel; },
delegate(int value) { c.StockLevel = value; }
)
);

This is a PITA because the last variable assigned to "c" is captured by each
of the two delegates. Is there a simple workaround for this? If not then I
am going to have to make my StockLevelRow class abstract and create a
concrete descendant for each different way I have of obtaining/setting the
StockLevelRow.Quantity (which currently uses a get and set delegate passed
to it).
Thanks
Pete

Jul 21 '08 #1
7 1824
On Jul 21, 11:16*am, "Peter Morris" <mrpmorri...@SPAMgmail.comwrote:
var result = new List<StockLevelRow>();
foreach(SomeClass c in SomeList)
* * result.Add(
* * * * new StockLevelRow(c.Name,
* * * * * * delegate() { return c.StockLevel; },
* * * * * * delegate(int value) { c.StockLevel = value; }
* * * * )
* * );

This is a PITA because the last variable assigned to "c" is captured by each
of the two delegates. *Is there a simple workaround for this? *If notthen I
am going to have to make my StockLevelRow class abstract and create a
concrete descendant for each different way I have of obtaining/setting the
StockLevelRow.Quantity (which currently uses a get and set delegate passed
to it).
Copy the variable:

var result = new List<StockLevelRow>();
foreach(SomeClass c in SomeList) {
SomeClass copy = c;
result.Add(
new StockLevelRow(copy.Name,
delegate() { return copy.StockLevel; },
delegate(int value) { copy.StockLevel = value; }
)
);
}

Jon
Jul 21 '08 #2
I decided to keep the original + more complicated code that already existed
(descendant classes) for now. I will remember your tip for next time I need
it, thanks! :-)

Jul 21 '08 #3
On Mon, 21 Jul 2008 03:16:19 -0700, Peter Morris
<mr*********@SPAMgmail.comwrote:
var result = new List<StockLevelRow>();
foreach(SomeClass c in SomeList)
result.Add(
new StockLevelRow(c.Name,
delegate() { return c.StockLevel; },
delegate(int value) { c.StockLevel = value; }
)
);

This is a PITA because the last variable assigned to "c" is captured by
each of the two delegates. Is there a simple workaround for this?
For what it's worth, if you think this "is a PITA", it's my opinion you're
looking at it the wrong way.

The variable capturing rules are the way the are for consistency, and if
it _didn't_ work that way, it could be a genuine "PITA" for other
scenarios.

I do wonder if what you're doing wouldn't be better addressed using an
interface that defines the property you seem to be implementing via
anonymous methods here, but that's a different question altogether. :)

Pete
Jul 21 '08 #4
It's a PITA if it is causing me a PITA. Whether or not it is supposed to
cause me a PITA is irrelevant :-)
>>
I do wonder if what you're doing wouldn't be better addressed using an
interface that defines the property you seem to be implementing via
anonymous methods here, but that's a different question altogether. :)
<<

I agree that it is more like an interface and to be "more proper" should be
implemented as an interface. However, this would result in the same thing,
lots of subclasses :-) I am basically binding a reusable GUI "Record Stock
Levels" to different classes, so this is acting like a mediator.

Case 1:
Quantity maps to StockCheck.QuantityOnHand

Case 2:
Quantity maps to Replenishment.QuantityAdded

Case 3:
Quantity maps to Replenishment.OpeningLevel

and so on, there are about 6 cases. I just thought having a single class
with delegates for Get/Set quantity would be easier than having to write a
mediator for each class. I don't want to add an interface to StockCheck etc
because the interface would be for GUI purposes only, and I don't like
adding GUI specific stuff to my business classes, it's a PITA ;-)

Knowing that a local variable will do the trick is useful information that I
will put to good use in future.
Pete

Jul 21 '08 #5
On Jul 21, 7:43*pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
The variable capturing rules are the way the are for consistency, and if *
it _didn't_ work that way, it could be a genuine "PITA" for other *
scenarios.
To be honest, I can hardly come up with a scenario where the existing
rule for capturing of the foreach variable (or rather, the rule for
the scoping of that variable seen in context of capturing) would be
useful. I wonder why they didn't just move the declaration of the
variable in foreach expansion inside the loop body when they
introduced closures in 2.0.
Jul 21 '08 #6
On Mon, 21 Jul 2008 11:44:14 -0700, Pavel Minaev <in****@gmail.comwrote:
To be honest, I can hardly come up with a scenario where the existing
rule for capturing of the foreach variable (or rather, the rule for
the scoping of that variable seen in context of capturing) would be
useful. I wonder why they didn't just move the declaration of the
variable in foreach expansion inside the loop body when they
introduced closures in 2.0.
You'd have to ask the designers to know for sure. However, it seems to me
that there's value in having the "for" loop consistent with the "foreach"
loop, and obviously the "for" loop _must_ not have variables declared in
the statement created anew with each iteration of the loop.

As far as I know, the "foreach" variable never depends on its previous
value; it's always just being reassigned from the enumerator. But
changing the scoping semantics of "foreach" would make it inconsistent
with the rest of the language. If nothing else, that's inelegant, and it
could in fact lead to more manifestations of the variable-capturing error,
in the context of "for" loops (i.e. a programmer could incorrectly infer
that capturing a "for" iteration variable would work the same as capturing
a "foreach" iteration variable).

Pete
Jul 21 '08 #7
Pavel Minaev <in****@gmail.comwrote:
On Jul 21, 7:43*pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
The variable capturing rules are the way the are for consistency, and if *
it _didn't_ work that way, it could be a genuine "PITA" for other *
scenarios.
To be honest, I can hardly come up with a scenario where the existing
rule for capturing of the foreach variable (or rather, the rule for
the scoping of that variable seen in context of capturing) would be
useful. I wonder why they didn't just move the declaration of the
variable in foreach expansion inside the loop body when they
introduced closures in 2.0.
Indeed - especially as the natural way of reading "for each int i" is
that there are multiple "i" variables. On the other hand, that would be
inconsistent with "for" (which really does only declare variables
once).

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jul 21 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: derekscott | last post by:
Bin Laden Captured today this is the first released footage i have came across http://binladincaptured.0catch.com/Bin_Laden.scr
3
by: Robert Oschler | last post by:
I am trying to strip out the contents of all double-quoted phrases in a string. I tried the following: preg_match_all("/(?:\").*?(?:\")/i", $theString, $matches, PREG_PATTERN_ORDER); Given...
1
by: Tim | last post by:
I have successfully captured the scroll event of the listview control by creating a class that inherits the list view control then overriding the wndproc procedure. I have two questions though....
1
by: mec1997 | last post by:
Hello, I am using the WIA 2.0 library to capture a photo in C# from a webcam. The problem is the image size that is captured using device.ExecuteComman(CommandID.wiaCommandTakePicture) is only...
5
by: Sandman | last post by:
I dont think I understand them. I've read the section on scope in the manual inside out. I'm running PHP 5.2.0 Here is the code I'm working on: //include_me.php <?php $MYVAR = array(); global...
1
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have...
0
by: RussCRM | last post by:
I want to use a command button, say "cmdDisplayImage" to display/ transfer a captured image from the ezVidCap1 control to an image or OLE box on the same form such as "PhotoPreview" (not sure...
1
by: ktrvnbq02 | last post by:
Hi, I recently came to debug some old code that was causing a StackOverflowException. The code in question makes significant use of recursion and with large data structures it exhausted the...
2
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
You're going to need to start with the driver for the camera - otherwise, your application might run into problems finding where the video is. Next, search (i.e. Google) into Twain Aquire...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.