Discussion:
Dynamic Casting in C#
(too old to reply)
Fazil Peermohammed
2009-09-01 15:06:22 UTC
Permalink
I'm writing a generic application that can read any .NET object which is a
wrapper on COM object (such as MS Exel 2007). I create the class in C# like
this:

ApplicationClass app = new ApplicationClass(); // the Excel application.

System.Reflection.PropertyInfo w = app.GetType().GetProperty("Workbooks");

Object Objbooks= w.GetValue(app, null);



Objbooks is now a System.__ComObject. My objective is to convert this to a
System.Object that represents Microsoft.Office.Interop.Excel.Workbooks. To
do this in C#, I would do



Microsoft.Office.Interop.Excel.Workbooks WorkBooks =
(Microsoft.Office.Interop.Excel.Workbooks)obj;



WorkBooks has all the properties and methods of Workbooks. How do I write
this casting algorithm dynamically so that I dont have to hard code any
type?



I've found a way to find the Type that represents
Microsoft.Office.Interop.Excel.Workbooks, but I just can't figure out how to
cast Objbooks to a System.Object of
Microsoft.Office.Interop.Excel.Workbooks.

I tried the generic method and reflection approach gievn in few sites, but I
still get a System.__ComObject without the properties of Workbooks.



Thanks

Fazil
Rich Lander [MSFT]
2009-09-04 14:22:30 UTC
Permalink
Post by Fazil Peermohammed
WorkBooks has all the properties and methods of Workbooks. How do I write
this casting algorithm dynamically so that I dont have to hard code any
type?
This is actually a bit of a problem. To my mind, the cast and the
assignment to a typed object are actually the least of your concerns.
The bigger problem is that you are likely going to want to call the
methods and properties exposed by this type across a number of lines
of code. How do you plan to do that in a dynamic way?

The meta issue is that you are trying to build a late-bound/dynamic
system with early-bound concepts and code. That's kinda hard. I'm
happy to go offline with you if you want more insight on this.

rich
Scott M.
2009-10-01 13:54:15 UTC
Permalink
And, remember all the necessary RealeasComObject(obj) calls or you are in
real trouble.

-Scott
Post by Rich Lander [MSFT]
Post by Fazil Peermohammed
WorkBooks has all the properties and methods of Workbooks. How do I write
this casting algorithm dynamically so that I dont have to hard code any
type?
This is actually a bit of a problem. To my mind, the cast and the
assignment to a typed object are actually the least of your concerns.
The bigger problem is that you are likely going to want to call the
methods and properties exposed by this type across a number of lines
of code. How do you plan to do that in a dynamic way?
The meta issue is that you are trying to build a late-bound/dynamic
system with early-bound concepts and code. That's kinda hard. I'm
happy to go offline with you if you want more insight on this.
rich
Loading...