c# - Create type by runtime type info using Activator<T>.CreateInstance() -


intro

to create instances on fly via reflection, use:

activator.createinstance  

the downside this returns object, while need concrete type , since know runtime type can't cast.

to accomplish this, can use

activator.createinstance<t> 

which returns t, since don't know t @ compile time, no use either. @ first glance anyway.

currently i'm using dynamic this, in special kind of way:

//i pass runtimetype itopsecret  // runtimetype implements itopsecret dynamic concretetypeinstance = activator.createinstance(runtimetype);  // have empty runtimetype.  // can use passed runtimetype fill newly created object concretetypeinstance = runtimetype  // call applycurrentvalues. // can't pass runtimetype, because it's itopsecret , // ef doesn't figure out actual runtime type. context.applycurrentvalues(concretetypeinstance) 

before line sanity checks performed. example know runtime type itopsecret @ point, otherwise statement can't hit.

so presumably reasonably safe. want, 1 line of code, seems great.

however i'm not sure intended way of using dynamic , if i'm setting door open nasty stuff.

why want this

currently have 1000s of lines of boilerplate code in many update methodes across various services. handcrafted, error-prone, repetetive, violates dry , makes harder new people. furthermore makes methods unclear losing focus on business logic and, frankly, plain ugly. usual suspects ;)

so i'm writing abstract/generic code factor out repetitive stuff. nice , cool bit of software write, leaves me (mostly) runtime info.

under surface these methods use entity framework , applycurrentvalues method. method requires concrete, instantianted, type , hence questions.

hope clear enough :)

questions

  • is ok way use dynamic, considering perform sanity checks before using it?
  • i feel there's way using reflection accomplish this. might worse in terms of performance, i'm curious if can done. possible create generic activator.createinstance<t> using reflection?
  • are either possibilities bad , should take different approach entirely? not knowing concrete types @ run-time, needing them anyway not can move away from.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -