Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Last active August 14, 2019 11:23
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/95fd288be27f0df5fae8ab5a093d36a4 to your computer and use it in GitHub Desktop.
Save ufcpp/95fd288be27f0df5fae8ab5a093d36a4 to your computer and use it in GitHub Desktop.
16.3 Preview 2 時点でいくつか確認
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
class Program
{
static void Main()
{
string? s1 = NullIfEmpty<string>(null); // 意図通り警告
string s2 = NullIfEmpty<string>(""); // 意図通り警告
if (TryParse("", out var x)) Console.WriteLine(x.X);
else Console.WriteLine(x.X); // 意図通り警告
string s3 = Id("");
string s4 = Id(null); // 意図通り警告
var s5 = Id(null);
Console.WriteLine(s5.Length); // 意図通り警告
}
[return: MaybeNull]
static T NullIfEmpty<T>(T a)
where T : IEnumerable
{
if (a.OfType<object>().Any()) return default; // これまだ警告残ってるんだ…
// ↑ 今のところそういう仕様っぽい。issue にはなってる。 https://github.com/dotnet/roslyn/issues/36039
return a;
}
static void AllowNull()
{
M(null); // ここで警告出ないのは意図通り
}
static void M([AllowNull] string s) => Console.WriteLine(s.Length); // 警告出さないと変
public static bool TryParse(
string? input,
[NotNullWhen(true)] out Point? value)
{
if(input is null)
{
value = null;
return false;
}
else
{
value = new Point();
return true;
}
}
[return: NotNullIfNotNull("s")]
static string? Id(string? s) => s;
private static void Exchange()
{
string? s = null;
System.Threading.Interlocked.CompareExchange(ref s, "", null);
Console.WriteLine(s.Length); // 警告出ない
System.Threading.Interlocked.CompareExchange(ref s, null, "");
Console.WriteLine(s.Length); // 警告出る
System.Threading.Interlocked.Exchange(ref s, "");
Console.WriteLine(s.Length); // 警告出ない
}
static void DoesNotReturn()
{
string? s = null;
Throw();
Console.WriteLine(s.Length); // 前まで警告出てた
}
[DoesNotReturn]
static void Throw() => throw new Exception();
static void DoesNotReturnIf()
{
string? s = null;
Loop(true);
Console.WriteLine(s.Length); // なんか 16.3 P2 でも動いてなさそう… 警告出る
}
static void Loop([DoesNotReturnIf(true)] bool b)
{
while (b) ;
}
void Equality(string x, string? y)
{
if (ReferenceEquals(x, y))
{
// x == y なら警告が消えるのに、ReferenceEquals だと残ってた。
// 16.3 Preview 1 の時点では警告あり、Preview 2 から消える。
Console.WriteLine(y.Length);
}
}
}
class Point
{
public int X { get; set; }
}
public class StrongBox<T>
{
// Public field that defaults to default(T)
[MaybeNull] public T Value;
// ここで警告出るの、マイルストーン vNext で issue 立ってた…
public StrongBox() { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment