Why is my C # method not called?

Why is my method X below not 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 to enter the debugger, but it does not enter X ! Is the yield break keyword causing a side effect that I don't know about?

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

+4
source share
3 answers

X2 is an iterator and runs with a delay. This will not be done until you try to get the value from the returned IEnumerable instance. You can fix this to get the behavior you really want by breaking the function 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 wonderful blog post on this subject: http://blogs.msdn.com/ericlippert/archive/2008/09/08/high-maintenance.aspx

+13
source

Yes, the method is not called until the IEnumerable GetEnumerator method is called.

+1
source

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

0
source

All Articles