Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8248075
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T23:04:29+00:00 2026-06-07T23:04:29+00:00

Possible Duplicate: C#: using the iterator variable of foreach loop in a lambda expression

  • 0

Possible Duplicate:
C#: using the iterator variable of foreach loop in a lambda expression – why fails?

I was reading c# reference at MSDN, and I found this..

http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx

at the end in comments there is one comment by albionmike
It goes like this..

When you "catpure" a variable from an outer scope, some counter-intuitive things happen.
If you run this, you will get an IndexOutOfRange exception during the call f().
If you uncomment the two commented out lines of code, it will work as expected.
Hint: Captured Outer Variables have reference rather than value semantics

// Console Project
using System;
using System.Collections.Generic;
using System.Text;


namespace EvilDelegation
{
    delegate void PrintIt();

    class Program
    {

        static void Main(string[] args)
        {
            string[] strings = { "zero", "one", "two", "three", "four" };
            PrintIt f = null;
            for (int i = 0; i < strings.Length; ++i) {
                if (i == 2 || i == 3) {
                    // Can you see why this would not work?
                    f = delegate() { Console.WriteLine(strings[i]); };

                    // But this does...
                    //int k = i;
                    //f = delegate() { Console.WriteLine(strings[k]); };

                }
            }
            f();
        }
    }
}

I don’t get it, why the fist one won’t work, and the second one will? In the 4th line, he says: Captured Outer Variables have reference rather than value semantics.
Okay, fine. But in the for loop, we defined i as an int which of course is a value type, so how can an int type hold a reference? And if i cannot hold reference, that means it is storing value, and if it is storing value, then I don’t get why the first one wont work and second one will?
Am I missing something here?

EDIT : I think the original author had a typo the call to f() should have been inside the if loop. Please consider that this while answering.

EDIT 2 : Okay, in case someone might say, it was not a typo, let consider that it was. I wanna know the case where the call to f() is made inside the if clause. Would both run in that case, or just the one not commented?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T23:04:31+00:00Added an answer on June 7, 2026 at 11:04 pm

    This is because of the semantics of closures. When a closure references a local variable in its outer scope, it captures a reference to the variable, not the value contained in the variable.

    In this case, the anonymous delegate delegate() { Console.WriteLine(strings[i]); } is capturing a reference to the i variable; that is, the variable is shared between the anonymous function and the scope in which i was declared. When i changes in one context, it also changes in the other.

    For example (see it run):

    using System;
    
    class Foo {
        static void Main() {
            int i = 0;
            Action increment = delegate { ++i; };
    
            Console.WriteLine(i);
    
            ++i;
            Console.WriteLine(i);
    
            increment();
            Console.WriteLine(i);
    
            ++i;
            Console.WriteLine(i);
    
            increment();
            Console.WriteLine(i);
        }
    }
    

    This will output:

    0
    1
    2
    3
    4
    

    In C#, the lifetime of a local is extended to include the lifetime of any closures that reference them. This enables some pretty interesting tricks that may offend the sensibilities of C/C++ developers:

    static Func<int> Counter() {
        int i = 0;
        return delegate { return i++; };
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: C#: using the iterator variable of foreach loop in a lambda expression
Possible Duplicate: encode json using php? $hello_world = $this->session->all_userdata(); foreach($hello_world as $key=>$product_id) { $query['products']
Possible Duplicate: Using a javascript variable to set PHP variable I need to do
Possible Duplicate: Using regular expression within a stored procedure I need to validate a
Possible Duplicate: Using var outside of a method I've searched for this a bit,
Possible Duplicate: Using bind1st for a method that takes argument by reference I have
Possible Duplicate: Using delegate() with hover()? I am trying this code, but apparently I
Possible Duplicate: PHP Using a variable when calling a static method I've read through
Possible Duplicate: Loading model using Jeff Lamarches script Guys this might sound very newbie
Possible Duplicate: Using Git with an existing Xcode project Setting up a git repository

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.