Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm seeing a pattern throughout my code where the lambda expression is showing as not covered in code coverage, the debugger DOES step through the code and there are no conditional blocks.

public CollectionModel()
{
    List<Language> languages = LanguageService.GetLanguages();
    this.LanguageListItems =
        languages.Select(
            s =>
            new SelectListItem { Text = s.Name, Value = s.LanguageCode, Selected = false }). // <-- this shows as not covered
            AsEnumerable();
}

It is somewhat odd. Any ideas?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

What I think you mean is that the debugger is not stepping over the indicated line; is that right?

If that's your question, then the answer is that, at least in this particular case, what you are seeing is deferred execution. All of the LINQ extension methods provided by System.Linq.Enumerable exhibit this behavior: namely, the code inside the lambda statement itself is not executed on the line where you are defining it. The code is only executed once the resulting object is enumerated over.

Add this beneath the code you have posted:

foreach (var x in this.LanguageListItems)
{
    var local = x;
}

Here, you will see the debugger jump back to your lambda.

share|improve this answer
    
+1. Alternatively, he couly use ToList instead of AsEnumerable and have the same effect. –  nikie Sep 13 '10 at 14:43
1  
@nikie: Yeah, but I wanted him specifically to see the debugger jump back to the lambda upon iteration as I feel that makes it unmistakably clear what's going on. –  Dan Tao Sep 13 '10 at 14:46
2  
Note also that if the collection is empty then the projection will never be called even if the collection is iterated. –  Eric Lippert Sep 13 '10 at 17:33
    
the debugger DOES step through this. Which is why its so confusing. My company wants us to use AsEnuerable instead of list for some reason. –  wcpro Sep 15 '10 at 3:05
    
you guys are absolutely right.. The code executes propertly when enumerated with ToList() –  wcpro Sep 15 '10 at 14:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.