reflection - Can I set the type of a field within a class at runtime to a newly created type in c#? -


i'm using reflection.emit , typebuilder create new type @ runtime. setup like:

public class myclass {     public object myfield = createinstanceofnewtype();     public myclass() {} } 

the issue myclass.myfield declared type object , implicit cast operators exist new type not called when castable types assigned myclass.myfield. there way set type of field newly created type behaves how in typical case?

this depends on exact use case, possible solution make class generic, use reflection create static generic method creates instance of class. allows use variable dynamic type when declaring property:

public class myclass<t> {  public t myfield = createinstanceofnewtype<t≥();  public myclass() {}  }  public static myclass<t> createclass<t>() { return new myclass<t>: }  dynamic instanceofmyclass = typeof(someclass).getmethod("createclass").makegeneric(dynamictype).invoke() 

another alternative using dynamic keyword.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -