Skip to content

Method with IEnumerable return type is not executed when expected

April 27, 2011

See the following short sample:

	class Program
		static void Main(string[] args)
			Items<int> items = new Items<int>();

	public class Items<T>
		public IEnumerable<T> GetItems()
			Console.WriteLine("GetItems called");
			yield break;

The evident question would be after seeing this code : What is written to the console?
The first answer would be “GetItems called” but that’s the wrong answer. The right answer is nothing because the enumerator is not executed by the .NET framework until its first element is referenced. So in the above code the GetItems method is never executed.

However if we start to iterate through the items, the enumerator is called as we would expect. To see it, just replace the item.GetItems() line with a foreach, like foreach (var i in items.GetItems()) {}


From → .NET

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: