Created
August 2, 2019 05:00
-
-
Save ufcpp/bd074a6d8d1eb049d1eba78630a652e5 to your computer and use it in GitHub Desktop.
safe な C# ではありえないはずの null 参照
This file contains 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; | |
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