C# casting issues.

D

DJ

Anyone know how to cast an object to the value of a System.Type
variable. I have a list of WebServices that have identical methods
and I want to create a wrapper class for them with the same methods.
But, if I store the web service as an object and the type as a
System.Type I can't seem to cast the object using the type to access
the methods. It's an issue of dynamic casting. This is the basic idea:

// store the web service as an object.
object item = new Company.WebService();
// store the type of the web service.
System.Type type = typeof(Company.WebService);
// cast the object as the web service type to access the methods.
int result = ((type)(item)).method(params); // <- this step doesn't
work

The error it gives me is that "type" is a field and not a class. So
how do I represent "type" as the class value it holds so that I can
compile without it barking at me.

Any help would be appreciated.
~DJ
 
M

Michael A. Covington

I think you are going to have to call a casting method in System.Type rather
than using the C# casting syntax.

But at the moment I can't lay hands on the exact way to do this.
 
R

Richard A. Lowe

If you don't have a design-time available type (either a common interface or
base class) that the web service has implemented so that you can cast to it,
you will have to use reflection by calling InvokeMember() on the type to
call the method.

Richard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top