Skip to content

Instantly share code, notes, and snippets.

@Sergio0694
Created September 21, 2019 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sergio0694/969d0a9b898fac4fef6ce62e0e8e4ba5 to your computer and use it in GitHub Desktop.
Save Sergio0694/969d0a9b898fac4fef6ce62e0e8e4ba5 to your computer and use it in GitHub Desktop.
public static void EmitStoreToAddress(this ILGenerator il, Type type)
{
if (type.IsValueType)
{
// Pick the optimal opcode to set a value type
OpCode opcode = Marshal.SizeOf(type) switch
{
// Use the faster op codes for sizes <= 8
1 when type == typeof(byte) || type == typeof(sbyte) => OpCodes.Stind_I1,
2 when type == typeof(short) || type == typeof(ushort) => OpCodes.Stind_I2,
4 when type == typeof(float) => OpCodes.Stind_R4,
4 when type == typeof(int) || type == typeof(uint) => OpCodes.Stind_I4,
8 when type == typeof(double) => OpCodes.Stind_R8,
8 when type == typeof(long) || type == typeof(ulong) => OpCodes.Stind_I8,
// Default to stobj for all other value types
_ => OpCodes.Stobj
};
// Also pass the type as argument if stobj is used
if (opcode == OpCodes.Stobj) il.Emit(opcode, type);
else il.Emit(opcode);
}
else il.Emit(OpCodes.Stind_Ref);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment