C# Yield issue
Clever Code
1
Posts
1
Posters
3
Views
1
Watching
-
Stumbled across this one when implementing a DataSourceControl for ASP.NET. Here is a simplified code, for a practical case where this bug may occur see ExecuteSelect[^] method.
public class EnumeratorSpec
{
public int MaxRecords;
};class Program
{
public static IEnumerable GetEnumerableAndCount(EnumeratorSpec spec)
{
spec.MaxRecords = 20;for (int i = 0; i < 20; i++) { yield return i + 1; } } static void Main(string\[\] args) { EnumeratorSpec spec = new EnumeratorSpec(); IEnumerable results = GetEnumerableAndCount(spec); Console.WriteLine("Results {0}", spec.MaxRecords); if (spec.MaxRecords != 0) { foreach (int result in results) { Console.WriteLine(result); } } }
}
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan