c# - How to instantiate an object of a type passed by parameter, that needs to implement a certain interface? -


lets have interface called imyinterface, , class called myclass implements imyinterface

in class have method has type parameter , type must implement imyinterface valid. e.g. myclass valid argument. in method instantiate object of type passed parameter.

how achieve this? if not possible, solution have similar effect?

there 2 parts of answer. first should validate type type.isassignablefrom:

var implementinterface = (typeof(imyinterface)).isassignablefrom(type); if(!implementinterface)     // return null, throw exception or handle scenario in own way 

next can instantiate object. here several ways can create object of type on fly, 1 use activator.createinstance:

// create object of type var obj = (imyinterface)activator.createinstance(type); 

and you'll instance of myclass in obj.

another way use reflection:

// public constructors var ctors = type.getconstructors(bindingflags.public);  // invoke first public constructor no parameters. var obj = ctors[0].invoke(new object[] { }); 

and 1 of constructorinfo returned, can "invoke()" arguments , instance of class if you've used "new" operator.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -