Reputation: 2513
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?
Upvotes: 1
Views: 218
Reputation: 16439
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 by initobj <type>
.
initobj
is normally used for structs (default(MyStruct)
in C#), but it should also work for primitive types.
Upvotes: 0
Reputation: 171188
There is no such method built-in. You can create a helper by yourself and have the problem solved for all time.
That said, you can use expression trees and have the emit code into an ILGenerator of your choice. This means you can generate not only dynamic methods but use them to fill your TypeBuilder-created methods.
Upvotes: 0
Reputation: 12425
Have you considered using .Net expression trees instead?
http://msdn.microsoft.com/en-us/library/bb397951.aspx
Upvotes: 1