Skip to content

Instantly share code, notes, and snippets.

@jonathanvdc
Last active August 27, 2015 16:28
Show Gist options
  • Save jonathanvdc/4386789b882d1947e8b0 to your computer and use it in GitHub Desktop.
Save jonathanvdc/4386789b882d1947e8b0 to your computer and use it in GitHub Desktop.
call vs newobj in struct initialization
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class Program
{
public static void Main(string[] args)
{
var dangerousStruct = new TestStruct(0);
dangerousStruct.X = 5;
dangerousStruct = new TestStruct(0);
/*
Release mode:
IL_0000: ldc.r8 0.0
IL_0009: newobj instance void [StructInitTest]TestStruct::.ctor(float64)
IL_000e: pop
IL_000f: ldc.r8 0.0
IL_0018: newobj instance void [StructInitTest]TestStruct::.ctor(float64)
IL_001d: pop
Release output:
0
0
*/
/*
Debug mode:
IL_0001: ldloca.s dangerousStruct
IL_0003: ldc.r8 0.0
IL_000c: call instance void [StructInitTest]TestStruct::.ctor(float64)
IL_0011: nop
IL_0012: ldloca.s dangerousStruct
IL_0014: ldc.r8 5
IL_001d: stfld float64 [StructInitTest]TestStruct::X
IL_0022: ldloca.s dangerousStruct
IL_0024: ldc.r8 0.0
IL_002d: call instance void [StructInitTest]TestStruct::.ctor(float64)
Debug output:
0
5
*/
}
}
}
// Metadata version: v4.0.30319
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly StructInitTest
{
.ver 0:0:65535:65535
}
.module StructInitTest
// MVID: {87E574D7-FDDD-4E55-9A84-09B93E156F07}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00000001 // ILONLY
// Image base: 0x0000001C4C130000
// =============== CLASS MEMBERS DECLARATION ===================
.class public auto ansi sealed beforefieldinit TestStruct
extends [mscorlib]System.ValueType
{
.field public float64 X
.method public hidebysig specialname rtspecialname
instance void .ctor(float64 y) cil managed
{
.maxstack 8
// This value type is purposefully left uninitialized.
ldarg.0
ldfld float64 TestStruct::X
call void [mscorlib]System.Console::WriteLine(float64)
ret
} // end of method TestStruct::.ctor
} // end of class TestStruct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment