Shane
Shane

Reputation: 1216

Using methods of an object without casting

I have a problem with casting/types and so on.

Firstly, my query is a follow on from another post here: Initialize generic object from a System.Type

so to continue on from this question, how can I use the methods of my newly created object?

i.e. what I want to do is as follows:

Type iFace = typeof(IService1);
Type genericListType = typeof(System.ServiceModel.ChannelFactory<>).MakeGenericType(iFace);
object factory = Activator.CreateInstance(genericListType, new object[]
                    {
                        new BasicHttpBinding(),
                        new EndpointAddress("http://localhost:1693/Service.svc")
                    });
var channel = factory.CreateChannel();

by the way, although I am using this application for WCF, this is not a WCF problem

Upvotes: 1

Views: 1075

Answers (2)

bniwredyc
bniwredyc

Reputation: 8839

Without dynamic objects:

object factory = Activator.CreateInstance(genericListType, new object[]
{
    new BasicHttpBinding(),
    new EndpointAddress("http://localhost:1693/Service.svc")
});

Type factoryType = factory.GetType();
MethodInfo methodInfo = factoryType.GetMethod("CreateChannel");
var channel = methodInfo.Invoke(factory) as YourChannelType;

Upvotes: 2

Anders Arpi
Anders Arpi

Reputation: 8417

Try using a dynamic object? This allows you to call methods that might or might not exist.

Upvotes: 2

Related Questions