Feb 27, 2023

Diversão com referências em C# - Parte I / II

Read this post in English.

Lire cet post en Français.

Vou começar os posts de 2023 (no final de Fevereiro :)) com um pequeno quebra-cabeças em C#.

Dado o programa abaixo, responda as seguintes questões:

1. O que será impresso?

2. Você é capaz de apontar/explicar os problemas no mesmo?

3. Como poderíamos notar o problema apenas fazendo inspeção do código?

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);
}
}

Claro que você pode compilar/rodar o programa (inclusive eu recomendo que você o faça), contudo seria interessante criar uma hipotese antes.

Até o próximo post.

Divirta se!

Adriano

No comments: