1
Vote

Exception when return type is struct such as Guid

description

I got an error when I had a service return a Guid which is a value type but not a pritive. I was able to fix it with the code below, checking for IsPrimitive and if not, returning Ldobj.
if (returnType != typeof(void))
{
    mIL.Emit(OpCodes.Ldloc, resultLB.LocalIndex); //load the result array
    mIL.Emit(OpCodes.Ldc_I4, 0); //load the index of the return value. Alway 0
    mIL.Emit(OpCodes.Ldelem_Ref); //load the value in the index of the array

    if (returnType.IsValueType)
    {
        mIL.Emit(OpCodes.Unbox, returnType); //unbox it
        if (returnType.IsPrimitive) //deal with primitive vs struct value types
            mIL.Emit(ldindOpCodeTypeMap[returnType]);
        else
            mIL.Emit(OpCodes.Ldobj, returnType);
    }
    else
        mIL.Emit(OpCodes.Castclass, returnType);
}

comments