简体   繁体   中英

Extension method throws exception only when debugging

I am using the following extension method ( from an existing StackOverflow question ) to split an existing enumerable into two:

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
    int i = 0;
    var splits = from item in list
                 group item by i++ % parts into part
                 select part.AsEnumerable();
    return splits;
}

I am using the method like so:

//accountIds is simply an IEnumerable<string>
var foo = accountIds.Split(2).ToList();

The method seemingly works fine when I run my application. However, when I debug my application this line of code always throws an exception:

Object reference not set to an instance of an object.

I am very confused why this method only throws an exception when I am debugging.

I'm not sure about this, but I think you should evaluate it first. You can use .ToArray() or .ToList() method.

Have a look on Jon Skeet blog on captured variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM