ASP.NET - IEnumerable return type

Asked By sri on 21-Feb-12 01:34 AM
 public static IEnumerable<emp> getemp1()
         {
 SqlConnection sConn = new SqlConnection("Data Source=xxxxx;Initial Catalog=xx; User ID=xxxx;Password=xxx");
          SqlCommand cmd = new SqlCommand();
            SqlCommand sComm = new SqlCommand("Select EmpNo, Ename from emp", sConn);
            sComm.CommandType = CommandType.Text;
            sComm.Connection = sConn;
            //sComm.ExecuteReader();
             dr = sComm.ExecuteReader();


            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    yield return emp.CreateNew(dr);
                }
            }
            dr.Close();
            sConn.Close();
         }

IEnumerable return type
Somesh Yadav replied to sri on 21-Feb-12 02:07 AM
Hi,

Try this,

Method with IEnumerable return type is not executed when expected


See the following short sample:

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

    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()) {}

Hope it helps.