✅ Setting default values on fields when generating runtime type
Hi all,
I've got code here that is generating a run-time type using
TypeBuilder
, FieldBuilder
and PropertyBuilder
. I'd like to ensure that fields have certain default values, as if I'd defined them in the class definition. How can I do this? Currently, if an auto property is defined as being a string
, when I create an instance of the runtime type, this property is null
6 Replies
You'd have to IL emit a constructor
ah - okay. I'm currently using a default constructor, but I'll change this to be a custom (parameterless) one
I guess if this is all dealt with in the constructor, that answers my follow-up question, which is how to determine what the default value is in a compiler-time type - I had thought I was doing this a hacky way by creating an instance and then querying it, but I guess that's how this should be done
Sorry, a little confused. You have a
Type
and want to know how to get a default(T)
of that type? Or whether any given value is a default(T)
?Ah, no - I have something like this:
And I want to take
typeof(MyType)
and be able to turn it into json something like this:
This is a simplified version of what I'm actually currently doing, but includes the default valuesOh, yeah those default values aren't in the metadata. Creating an instance and querying them is likely your best bet.
cool stuff - thanks for the help
(these are running in two processes, and I want to be able to only have some types defined in one of the processes, but able to be passed through the other - these two examples are the two ends of the processes)