Click here to Skip to main content
15,906,766 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am demoing a Console Application to try out the Yield Keyword. This is my code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YieldKeyword
{
    class Program
    {
        static List<int> MyList = new List<int>();

        static void FillValues()
        {
            MyList.Add(1);
            MyList.Add(2);
            MyList.Add(3);
            MyList.Add(4);
            MyList.Add(5);
        }
        static IEnumerable<int> FilterWithoutYield()
        {
            List<int> temp = new List<int>();
            foreach (int i in MyList)
            {
                if (i > 3)
                {
                    temp.Add(i);
                }
            }
            return temp;
        }
        static IEnumerable<int> FilterWithYield()
        {
            foreach (int i in MyList)
            {
                if (i > 3) yield return i;
            }
        } 
        static void Main(string[] args)
        {
            FillValues();
            //IEnumerable<int> temp = new List<int>();
            //temp = FilterWithoutYield();
            FilterWithYield();
            foreach (int i in MyList)
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }
    }
}



However, the control never passes to the
FilterWithYield
method. Why is this happening ? What am I doing wrong ?
Posted

1 solution

You're not doing anything with the values returned from FilterWithYield so it's optimized out.

Change
C#
FilterWithYield();
foreach (int i in MyList)
{
  Console.WriteLine(i);
}

to
C#
foreach (int i in FilterWithYield())
{
  Console.WriteLine(i);
}

And you should see the method being hit.

Hope this helps,
Fredrik
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900