Skip to content

Instantly share code, notes, and snippets.

@adrianoc
Last active February 15, 2023 13:24
Show Gist options
  • Save adrianoc/2d02072fc7a75218fabce92e9b0a90a6 to your computer and use it in GitHub Desktop.
Save adrianoc/2d02072fc7a75218fabce92e9b0a90a6 to your computer and use it in GitHub Desktop.
Blog: Fun with references in C#
using System;
ref struct RefStruct
{
public RefStruct(ref int i) => value = ref i;
public ref int value;
}
partial class C
{
public static RefStruct Instantiate(ref int i) => new RefStruct(ref i);
unsafe static RefStruct InstantiateAndLog(int v)
{
Console.WriteLine($"{nameof(RefStruct)} created.");
return Instantiate(ref v);
}
public static void M2(int v)
{
Console.WriteLine("---------M2----------");
var rs = Instantiate(ref v);
Dump(rs);
}
public static void M3(int v)
{
Console.WriteLine("---------M3----------");
var rs = InstantiateAndLog(v);
Dump(rs);
}
static void Dump(in RefStruct rs)
{
var bytes = BitConverter.GetBytes(rs.value);
foreach(var b in bytes)
Console.WriteLine($"{b,2:x}");
}
static void Main()
{
const int Value = 0x01020304;
M2(Value);
M3(Value);
}
}
@adrianoc
Copy link
Author

Original idea:

using System;
partial class C
{
    public unsafe static Span<byte> CreateSpan(ref int  i)
    {
        return new Span<byte>(System.Runtime.CompilerServices.Unsafe.AsPointer(ref i), sizeof(int));
    } 
}

unsafe partial class C
{
    public static Span<byte> M(int i)
    {
        return CreateSpan(ref i);
    }
    
    public static void M2(int v)
    {
        var s = CreateSpan(ref v);
        Dump(s, "M2");
    }
    
    public static void M3(int v)
    {
        var s = M(v);
        Dump(s, "M3");
    }
    
    static void Dump(in Span<byte> span, string msg)
    {
        Console.WriteLine($"---------{msg}----------");
        for(var i = 0; i < span.Length; i++)
            Console.WriteLine($"{span[i],2:x}");
    }
    
    static void Main()
    {
        const int Value = 0x01020304;
        M2(Value);
        M3(Value);
    }    
}

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