c# Create generic list dynamically at runtime -


following example on this post, found out how create list of generic types dynamically. now, issue want add items created list unknown source list - there way achieve this?

edit start source list containing business objects, absolutely need right type of output list, because of downstream bindings require it.

my non-compiling code follows:

ilist<object> sourcelist; // list containing custom objects type t = typeof(ilist).makegenerictype(sourcelist[0].gettype()); ilist res = (ilist)activator.createinstance(t); foreach (var item in sourcelist) {     reportds.add(item); // not compile } 

i recommend moving code generic class or function, moving reflection higher level:

private static list<t> clonelistas<t>(ilist<object> source) {     // here can want t     // t == source[0].gettype()     return source.cast<t>().tolist(); } 

to call it:

ilist<object> sourcelist; // list containing custom objects // sourcelist = ...  methodinfo method = typeof(this).getmethod("clonelistas"); methodinfo genericmethod = method.makegenericmethod(sourcelist[0].gettype());  var reportds = genericmethod.invoke(null, new[] {sourcelist}); 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

android - CoordinatorLayout, FAB and container layout conflict -