C
C#7mo ago
Hugh

✅ 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
Tinister
Tinister7mo ago
You'd have to IL emit a constructor
Hugh
Hugh7mo ago
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
Tinister
Tinister7mo ago
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)?
Hugh
Hugh7mo ago
Ah, no - I have something like this:
public class MyType
{
public string ValueA { get; set; } = "default_a";
public string ValueB { get; set; } = "default_b";
public int ValueC { get; set; } = 5;
}
public class MyType
{
public string ValueA { get; set; } = "default_a";
public string ValueB { get; set; } = "default_b";
public int ValueC { get; set; } = 5;
}
And I want to take typeof(MyType) and be able to turn it into json something like this:
{
"name": "MyType",
"properties": [
{
"name": "ValueA",
"type": "string",
"default": "default_a"
},
{
"name": "ValueB",
"type": "string",
"default": "default_b"
},
{
"name": "ValueC",
"type": "int",
"default": 5
}
]
}
{
"name": "MyType",
"properties": [
{
"name": "ValueA",
"type": "string",
"default": "default_a"
},
{
"name": "ValueB",
"type": "string",
"default": "default_b"
},
{
"name": "ValueC",
"type": "int",
"default": 5
}
]
}
This is a simplified version of what I'm actually currently doing, but includes the default values
Tinister
Tinister7mo ago
Oh, yeah those default values aren't in the metadata. Creating an instance and querying them is likely your best bet.
Hugh
Hugh7mo ago
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)