Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Last active November 8, 2022 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufcpp/19d090babe824ab3fc064203b50de684 to your computer and use it in GitHub Desktop.
Save ufcpp/19d090babe824ab3fc064203b50de684 to your computer and use it in GitHub Desktop.
Ref Fields bug in VisualStudio 17.4 Preview 2
int i = 0;
int j = 0;
int a, b;
var t0 = new RefTuple();
(a, b) = t0;
t0.Deconstruct(out a, out b);
(a, b) = new RefTuple(ref i, ref j); // CS8347
var t1 = new RefTuple(ref i, ref j);
(a, b) = t1; // CS8352
t1.Deconstruct(out a, out b);
(a, b) = new RefTuple { A = ref i, B = ref j }; // CS8168
var t2 = new RefTuple { A = ref i, B = ref j };
(a, b) = t2; // CS8352
t2.Deconstruct(out a, out b);
(a, b) = getTuple(ref i, ref j); // CS8347
var t3 = getTuple(ref i, ref j);
(a, b) = t3; // CS8352
t3.Deconstruct(out a, out b);
static RefTuple getTuple(ref int a, ref int b) => new(ref a, ref b);
ref struct RefTuple
{
public ref int A;
public ref int B;
public RefTuple(ref int a, ref int b)
{
A = ref a;
B = ref b;
}
public void Deconstruct(scoped out int a, scoped out int b)
{
a = A;
b = B;
}
}
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
var a = new Array4<int>();
a[0] = 1; // CS8168
Console.WriteLine(a[0]); // CS8168
ref struct Array4<T>
{
#pragma warning disable IDE0044, IDE0051, CS0169
T _x0, _x1, _x2, _x3;
#pragma warning restore IDE0044, IDE0051, CS0169
[UnscopedRef]
public ref T this[int index] => ref Unsafe.Add(ref _x0, index);
[UnscopedRef]
public ref T GetPinnableReference() => ref _x0;
}
ref var r = ref m();
static ref int m()
{
int i = 0;
return ref m1(ref i).Item1;
static Ref m1(scoped ref int i) => new(ref i); // A scoped ref parameter passed to new Ref() as unscoped ref.
}
#if false
static ref int m(scoped ref int i) => ref i; // CS8166
#endif
#if false
static ref int m()
{
int i = 0;
return ref m1(ref i).Item1; // CS8168, CS8347
static Ref m1(ref int i) => new(ref i);
}
#endif
ref struct Ref
{
public ref int Item1;
public Ref(ref int item1) => Item1 = ref item1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment