I have metaprogramm, that needs to create code for initializing value fields.
I.e. have class
class Class1
{
int i;
double t;
Class1()
{
i=5;
t=3;
}
}
In reflection this looks like follow:
...
gen.Emit(OpCodes.Ldc_I4,5);
...
gen.Emit(OpCodes.Ldc_R8,3);
...
I don’t want to have a huge switch like this:
switch(t)
{
case typeof(int): gen.Emit(OpCode.Ldc_I4,value); break;
case typeof(double): gen.Emit(OpCodes.Ldc_R8,value); break;
// and so on for all value types
}
Is there some universal load value on evaluation stack OpCode? Or I need to have switch mentioned above?
Both fields and local variables start at zero by default, so you likely don’t need this.
For setting a variable to its default value, you can use
ldloca <variable>followed byinitobj <type>.initobjis normally used for structs (default(MyStruct)in C#), but it should also work for primitive types.