My understanding is that if an object that implements IDisposable
pattern is called within a foreach loop, its got disposed automatically without need to use it in a using or calling Dispose
method explicitly. I have following code
class Program
{
static void Main(string[] args)
{
using (Employee e = new Employee() { Name = "John" }) ;
{
}
foreach (var e in GetEmployees())
Console.WriteLine(e.Name);
}
static List<Employee> GetEmployees()
{
Employee emp = new Employee() { Name = "Peter" };
Employee emp2 = new Employee() { Name = "Smith" };
List<Employee> emps = new List<Employee>();
emps.Add(emp);
emps.Add(emp2);
return emps;
}
}
class Employee : IDisposable
{
public string Name { get; set; }
public void Dispose()
{
Console.WriteLine("disposing " + Name);
}
}
I don't see Dispose
is called for objects returned by GetEmployees
method. Does it mean I need to call Dispose
within foreach loop?