Search code examples
c#dispose

What is the proper way to use IDisposable?


In the example below... Since the class have an IDisposable interface and the class is itself is only a manage memory objects (not an unmanaged memory), so in the script further down below (See case #1 and case #2) - what is the proper way to do Disposal when done w/ the list objects?

 public class VehicleA : IDisposable
 {
     public void Dispose() { }

     public string Year {get;set;}
     public string Make {get;set;}
     public string Model {get;set;}
 }
 public class repositoryVehicle()
 {
     public List<VehicleA> VehicleLookup()
     {
         List<VehicleA> returnVehicles = new List<Vehicle>();

         returnVehicles.Add(new VehicleA { Year="2007", Make="Ford", Model="Mustang" });
         returnVehicles.Add(new VehicleA { Year="2004", Make="Chevy", Model="Blazer" });

         return returnVehicles;
     }
 }

 //Case #1...
 foreach(var v in repositoryVehicle.VehicleLookup())
 {
     //v.Year...
 }

 //Case #2...
 List<VehicleA> vehicles = new List<VehicleA>();
 vehicles = repositoryVehicle.VehicleLookup();
 //vehicles[x].Year...

Solution

  • The dispose pattern is used only for objects that access unmanaged resources. This is because the garbage collector is very efficient at reclaiming unused managed objects.

    There is no performance benefit in implementing the Dispose method on types that use only managed resources (such as arrays) because they are automatically reclaimed by the garbage collector. Use the Dispose method primarily on managed objects that use native resources and on COM objects that are exposed to the .NET Framework. Managed objects that use native resources (such as the FileStream class) implement the IDisposable interface.

    http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx