Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you emit the default value of a type?

I want to implement an interface that automatically clears all local fields, so far I have:

// Implement IClearable
dynamicType.AddInterfaceImplementation(typeof(IClearable));

MethodBuilder clearnMethodBuilder = dynamicType.DefineMethod("Clear", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard);
ILGenerator clearMethodILGen = clearnMethodBuilder.GetILGenerator();

foreach (FieldBuilder localField in fields)
{
    clearMethodILGen.Emit(OpCodes.Ldarg_0);
    clearMethodILGen.Emit(OpCodes.Ldfld, localField);
    clearMethodILGen.Emit(OpCodes.??, Profit??);
}

clearMethodILGen.Emit(OpCodes.Ret);

How do I set the last step to save the default value over the field?

like image 722
sircodesalot Avatar asked Oct 04 '22 14:10

sircodesalot


1 Answers

something like:

clearMethodILGen.Emit(OpCodes.Ldfld, localField);
clearMethodILGen.Emit(OpCodes.Initobj, localField.FieldType);
like image 197
Peter Ritchie Avatar answered Oct 11 '22 03:10

Peter Ritchie