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);
}
}
Last active
June 24, 2024 23:37
-
-
Save 0x59R11/9226316e4d4d743b00ffb225d286c8de to your computer and use it in GitHub Desktop.
C# Boxing & Unboxing under the hood
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment