Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created August 2, 2019 05:00
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/bd074a6d8d1eb049d1eba78630a652e5 to your computer and use it in GitHub Desktop.
Save ufcpp/bd074a6d8d1eb049d1eba78630a652e5 to your computer and use it in GitHub Desktop.
safe な C# ではありえないはずの null 参照
using System;
using System.Runtime.CompilerServices;
public class Program
{
// safe な C# ではありえないはずの null 参照。
// だいぶ邪悪。
private unsafe static ref T NullRef<T>() => ref Unsafe.AsRef<T>(null);
private unsafe static bool IsNull<T>(ref T x) => Unsafe.AsPointer(ref x) == null;
static void Main()
{
var items = new[] { 1, 2, 3 };
for (int i = -1; i < 4; i++)
{
Console.WriteLine(IsNull(ref ElementAtOrNull(items, i)));
}
}
// 「有効性 + 参照」を返したいんだけど、
// (ref T)? (参照の nullable)とか (bool, ref T) (参照を含むタプル)とか作れない。
// NullRef とかいう邪悪なものを使って乗り切る。
static ref T ElementAtOrNull<T>(T[] items, int index)
{
if ((uint)index < (uint)items.Length) return ref items[index];
return ref NullRef<T>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment