-
-
Save adrianoc/2d02072fc7a75218fabce92e9b0a90a6 to your computer and use it in GitHub Desktop.
Blog: Fun with references in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original idea: