Home » excel » C# System.__ComObject returned when accessing Excel file

C# System.__ComObject returned when accessing Excel file

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am trying to access Excel file by code below:

Microsoft.Office.Interop.Excel.Application ObjExcel
  = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook book;
Microsoft.Office.Interop.Excel.Worksheet sheet;
Excel.Range range1 = null, range2 = null;
CultureInfo ci = new CultureInfo("en-US");
Thread thisThread = Thread.CurrentThread;
thisThread.CurrentCulture = new CultureInfo("en-US");
book = ObjExcel.Workbooks.Open(LinguisticInstructionsFileName);

At last line content of book variable is System.__ComObject while in different app code is working and variable has ...Excel.WorkbookClass.

So I would like to ask what might be the reason for this strange behavior. I already tried to call Workbooks.Open with extra Missing.Value args but result was the same.

How to&Answers:

.NET COM implementation uses proxy objects, these proxies are generated internally and derive from System.__ComObject so that’s a normal behaviour.
They are a sort of “dynamic objects”.
You can cast the __ComObject to the interface or the class you need.
You can cast it to WorkbookClass without problems.

It all depends on how you get the instance… if you create an object with new, for example, new WorkbookClass, C# will directly create the strong typed object.
Instead if the object is returned from a COM function or a property it returns often a __ComObject, this because the __ComObject can be almost everything and can be casted to several interfaces, of course C# don’t know what to return so it returns this special kind of “dynamic” object. These objects are called RCW that stands for Runtime Callable Wrapper.

A nice read can be http://www.codeproject.com/KB/cs/cominteropnet.aspx