Skip to content

Instantly share code, notes, and snippets.

@0x59R11
Last active June 24, 2024 23:37
Show Gist options
  • Save 0x59R11/9226316e4d4d743b00ffb225d286c8de to your computer and use it in GitHub Desktop.
Save 0x59R11/9226316e4d4d743b00ffb225d286c8de to your computer and use it in GitHub Desktop.
C# Boxing & Unboxing under the hood

Aware! It's Not user-friendly

Source code:

public struct MyStr
{
    public int Age;
    public string Name;
    public ushort Type;
}

public class Program
{
    public static void Main()
    {
        // Initialize structure
        MyStr str = new MyStr();
        str.Age = 0xDEAD;
        str.Name = "BEEF";
        str.Type = 3;

        // Getting address to Action method
        var actionMethod = typeof(Program).GetMethod("Action", BindingFlags.Static | BindingFlags.Public);
        RuntimeHelpers.PrepareMethod(actionMethod.MethodHandle);
        Console.WriteLine($"ActionMethod: " + ((ulong)(actionMethod.MethodHandle.GetFunctionPointer())).ToString("X"));

        // Delay
        Console.ReadLine();


        Action(str);
    }

    public static void Action(MyStr str)
    {
        Do1(str);

        // boxing
        object obj = str;

        Do2(obj);

        // Unboxing
        MyStr unboxed = (MyStr)obj;

        Do1(unboxed);
    }

    public static void Do1(MyStr str)
    {
        // ...
        Console.WriteLine(str);
    }

    public static void Do2(object o)
    {
        // ...
        Console.WriteLine(o);
    }
}

Native method body of Action(MyStr str) with comments

image_2024-06-25_02-14-05

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment