Alex
Alex

Reputation: 136

IndexOutOfRange Exception when calling .ToList()

I've got a List of entities called usages, from which I create an IEnumerable of entities of type AdminUsage, as follows:

var models = usages.Select(u => new AdminUsage(u));

when I call .ToList() on models I get an IndexOutOfRange exception with the message "Index was outside the bounds of the array."

Why could this be happening, and how can I successfully get a List of type AdminUsage from my original list usages?

Edit: Ok, so actually the index that was out of range was inside the AdminUsage constructor:

public AdminUsageModel(Usage usageDetails) { Title = usageDetails.UsageName[0] }

So my revised question is why is the exception only thrown on the call .ToList() and not on the original .Select()?

Upvotes: 0

Views: 1281

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

why is the exception only thrown on the call .ToList() and not on the original .Select()?

Because a Select() doesn't do anything, it's a promise. With ToList() you materialize that promise, so that's when the code is actually executed, and the exception thrown.

See also MSDN: IEnumerable<T>.Select():

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

See also Deferred execution and eager evaluation, Trying to understand how linq/deferred execution works.

Upvotes: 3

Related Questions