Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Dynamic Casting in C#

5 views
Skip to first unread message

Fazil Peermohammed

unread,
Sep 1, 2009, 11:06:22 AM9/1/09
to
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]

unread,
Sep 4, 2009, 10:22:30 AM9/4/09
to
> 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.

unread,
Oct 1, 2009, 9:54:15 AM10/1/09
to
And, remember all the necessary RealeasComObject(obj) calls or you are in
real trouble.

-Scott

"Rich Lander [MSFT]" <ri...@lander.ca> wrote in message
news:f8d40986-8009-42d9...@g1g2000pra.googlegroups.com...

0 new messages