0

Maybe this is by design, but could somebody explain why it behaves like this?

I'm writing an android app with Xamarin in Visual Studio 2015.

I downloaded this example, and was trying to make it a little more simpler to use.

Here is the method being called by my code, which works fine.

private List<Android.Support.V4.App.Fragment> _fragmentList = new List<Android.Support.V4.App.Fragment>();
public void AddFragmentView(Func<LayoutInflater, ViewGroup, Bundle, View> view)
{
    _fragmentList.Add(new GenericViewPagerFragment(view));
}

The next method works fine, as expected. I'm passing it a list of numbers associated with my layout files.

public void AddViewsToFragmentList(List<int> views)
{
    for(int j=0; j<views.Count; j++)
    {
        int viewIndex = views[j];
        AddFragmentView((i, v, b) =>
        {
            var view = i.Inflate(viewIndex, v, false);
            return view;
        }
        );
    }
}

Now, if I don't create the viewIndex variable first, but simply pass it that index, it is giving me an index out of range error.

public void AddViewsToFragmentList(List<int> views)
{
    for(int j=0; j<views.Count; j++)
    {
        AddFragmentView((i, v, b) =>
        {
            var view = i.Inflate(views[j], v, false);  //errors here when it gets to 3, which it should never reach
            return view;
        }
        );
    }
}

enter image description here Is there some reason why even though I told my loop to stop when it reaches the list count that it is still trying to run the code in my loop? Once j becomes 3, it should stop the loop and never get to that function, right?

jpaugh78
  • 99
  • 2
  • 10
  • 5
    It's a [Modified Closure](https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/) issue. – Matthew Watson Sep 23 '16 at 13:18
  • 2
    http://stackoverflow.com/a/12861740/40347 – Dirk Vollmar Sep 23 '16 at 13:18
  • 4
    The best solution to this is to change your `for` loop to a `foreach` loop, by the way. As of C# 5, that will work fine. – Jon Skeet Sep 23 '16 at 13:19
  • Okay, thanks @JonSkeet. I've seen `foreach` behave oddly sometimes when it comes to what order it goes in, but it looks like for List it should go in order of index so I should be fine. – jpaugh78 Sep 23 '16 at 13:26
  • 2
    @jpaugh78: Well `foreach` itself is fine... but for any collection, you should be aware of whether its order is guaranteed or not. (For example, dictionaries and hashsets are not.) – Jon Skeet Sep 23 '16 at 13:26
  • @JonSkeet Thanks again for the help. Sorry for making assumptions before making this post, but I had never run into this issue before. – jpaugh78 Sep 23 '16 at 13:31

0 Answers0