IDisposable and Marshal.ReleaseCOMObject and dynamic in C#

 

If you have worked with COM, you know that for every COM object that you access is not only necessary to null the reference, but also call Marshall.ReleaseCOMObject .

This is a very error prone task, because you have all try / finally blocks

 
// declare a, ws, w 
try{ 
a=new Application(); 
ws = a.Workbooks; 
w = ws.Add(); 
//code 
}
 catch(...) {
 if( w != null){ 
Marshal.ReleaseComObject(w); 
w = null; 
}
 if(ws !=null){ 
Marshal.ReleaseComObject(ws); 
ws = null; 
} 
if( a!= null) { 
Marshal.ReleaseComObject(a); a= null; 
} 
} 

All of this could be done easy with IDisposable, if

1. IDisposable calls the Marshal.ReleaseCOMObject

2. Find a way to call methods / properties on the COM object from the class that implements IDisposable

 

I have done this and the result is like this:

 
using (dynamic a = new ComDisposable(new Application())) { 
using (dynamic ws = a.Workbooks) { 
using (dynamic w = ws.Add()) { 
using (var shs = w.Sheets) { 
using (var s = shs[1]) { 
//Worksheet a; 
using (var r = a.Range("A1")) { 
r.Value2 = "http://ignatandrei.github.io/ToolsAndUtilities/";; 
using (var f = r.Font) { 
f.Bold = true; 
}
 }
 }
 }
 w.SaveAs(fileName); 
w.Close(); 
} 
}
 a.Quit(); } 

 

Video at https://youtu.be/2qbAcSjL1gU

NuGet package at https://www.nuget.org/packages/ReleaseComObjectDisposable/