Hosam Aly
Hosam Aly

Reputation: 42443

Why is my C# method not called?

Why is my X method below not being called?!

static class Program
{
    private static void Main()
    {
       X((IEnumerable<int>)null);
    }

    public static IEnumerable<T> X<T>(IEnumerable<T> e)
    {
        if (e == null)
            throw new ArgumentNullException();
        yield break;
    }
}

I tried stepping into the debugger but it doesn't enter X! Is the yield break keyword causing some side effect I am not aware of?

If it's worth anything, I'm using Visual Studio 2008 Express with .NET 3.5 SP1.

Upvotes: 5

Views: 5619

Answers (3)

sassafrass
sassafrass

Reputation: 250

Your Main() method also needs to be public. Otherwise, other assemblies can't invoke your class's Main() method as the starting point of the application.

Upvotes: 0

AnthonyWJones
AnthonyWJones

Reputation: 189437

Yes the method doesn't get called until the IEnumerable's GetEnumerator method is called.

Upvotes: 1

JaredPar
JaredPar

Reputation: 754565

X2 is an iterator and is delayed executed. It won't be actually run until you attempt to get a value from the returned IEnumerable instance. You can fix this to get the behavior you are actually wanting by breaking the function up into 2 parts.

   public static IEnumerable<T> X2<T>(IEnumerable<T> e)
   {
        if (e == null)
            throw new ArgumentNullException();
        return X2Helper(e);
    }

    private static IEnumerable<T> X2Helper<T>(IEnumerable<T> e)
    {
        yield break;
    }

Eric has a great blog post on this subject: http://blogs.msdn.com/ericlippert/archive/2008/09/08/high-maintenance.aspx

Upvotes: 13

Related Questions