yield return inside a using block

This a short post to act as a reminder.

I decided to refactor some code to return IEnumerable (using yield return) instead of returning an IList. So I have a method named Deserialize which creates a memory stream and then passes it to an overload which takes a Stream. For example

public IEnumerable<T> Deserialize(string data)
{
   using (MemoryStream memoryStream = new MemoryStream())
   {
      memoryStream.Write(Encoding.ASCII.GetBytes(data), 0, data.Length);
      memoryStream.Seek(0, SeekOrigin.Begin);

      return Deserialize(memoryStream);
   }
}

public IEnumerable<T> Deserialize(Stream stream)
{
   // does some stuff
   yield return item;
}

The unit tests thankfully spotted straight away a simple mistake. In that the using clause is exited before the first yield return takes place. So the stream is disposed of, and therefore invalid, when the overload tried to access it. Doh !

Thankfully it’s easy to fix using the following

public IEnumerable<T> Deserialize(string data)
{
   using (MemoryStream memoryStream = new MemoryStream())
   {
      memoryStream.Write(Encoding.ASCII.GetBytes(data), 0, data.Length);
      memoryStream.Seek(0, SeekOrigin.Begin);

      foreach (var item in Deserialize(memoryStream))
      {
         yield return item;
      }   
   }
}

Obviously we could have alternatively used something like

return new List<T>(Deserialize(memoryStream));

but this then negates the purpose of using the yield return in the first place.