Can I add new fields to an existing type using reflection( FieldBuilder) ?
-
Hi, If can, Could you please tell me how? Thanks!
Charith Jayasundara
-
Hi, If can, Could you please tell me how? Thanks!
Charith Jayasundara
You can't. Reflection tells you what is already there, it doesn't allow you to change the shape of the type.
Developer Day Scotland 2 - Free community conference Recent blog posts: *Throwing Exceptions *Training Developers * Method hiding or overriding - or the difference between new and virtual
-
You can't. Reflection tells you what is already there, it doesn't allow you to change the shape of the type.
Developer Day Scotland 2 - Free community conference Recent blog posts: *Throwing Exceptions *Training Developers * Method hiding or overriding - or the difference between new and virtual
You can however do that using Mono.Cecil opensource library, the trick is that cecil doesn't load the assembly into AppDomain, so you can make changes. Here is a code snippet for example: FieldDefinition field = new FieldDefinition("TestField", sometype, FieldAttributes.Private); sometype.Fields.Add(field); This adds a private field of type sometype to sometype. Unfortunately there is no documentation for cecil, but you can ask questions in the Mono Cecil Google Group[^]
Regards, Lev
-
You can however do that using Mono.Cecil opensource library, the trick is that cecil doesn't load the assembly into AppDomain, so you can make changes. Here is a code snippet for example: FieldDefinition field = new FieldDefinition("TestField", sometype, FieldAttributes.Private); sometype.Fields.Add(field); This adds a private field of type sometype to sometype. Unfortunately there is no documentation for cecil, but you can ask questions in the Mono Cecil Google Group[^]
Regards, Lev
"the trick is that cecil doesn't load the assembly into AppDomain" How this will affect the other stuff? Thanks!
Charith Jayasundara
-
"the trick is that cecil doesn't load the assembly into AppDomain" How this will affect the other stuff? Thanks!
Charith Jayasundara
What do you mean "other stuff"? You can edit the assembly using cecil, save it, and then do whatever you want to do with reflection (unless you get charmed by cecil and want to switch to it ;))
Regards, Lev