Jamie Dixon
Jamie Dixon

Reputation: 53991

Debugging an IEnumerable method

I have a method with returns an IEnumerable<T> and I'm trying to debug the code inside that method.

Each time I step through the code in Visual Studio during debug, it steps over the method in question.

When I place a breakpoint inside the method it never gets hit. The code is definately running as I've tested by yield return'ing fake T's from the method.

Is it not possible to debug IEnumerable methods this way or am I do something else wrong?

Upvotes: 25

Views: 8222

Answers (2)

alex2k8
alex2k8

Reputation: 43214

It should be no problem to debug IEnumerable implementation... May be you just using wrong .dll (if you enumerator is in external library)...

You may try a simple test console, and go from here

class Program
{
    static void Main(string[] args)
    {
        foreach (String foo in new Foo())
        {
            Console.WriteLine(foo);
        }
    }
}

class Foo : IEnumerable<String>
{
    #region IEnumerable<string> Members

    public IEnumerator<string> GetEnumerator()
    {
        yield return "fake # 1";
        yield return "fake # 2";
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion
}

Upvotes: 0

BFree
BFree

Reputation: 103742

That method only gets hit when you use the items in the IEnumerable. Remember, IEnumerable lazy loads the items, so just because you're calling the method that returns the IEnumerable, doesn't mean the method is actually getting called at that point. If you want it to get hit right when you call it, add a ToList() at the end of your method call:

var result = myEnumerableMethod().ToList();

Upvotes: 55

Related Questions