例えばswitch• パターン マッチングの拡充•そもそもC# 7.3の頃まではこんな書き方になってたstatic int CompareTo(int? x, int? y){if (x is int x1)if (y is int y1) return x1.CompareTo(y1);else return 1;elseif (y is int y1) return -1;else return 0;}
10.
参考• Preview版の頃から割と安定していた機能は4月の登壇を参照Visual Studio2019 Launch(https://connpass.com/event/122145/)C# 8.0 Preview in Visual Studio 2019 (16.0)(https://www.slideshare.net/ufcpp/c-80-preview-in-visual-studio-2019-160)
AllowNull• ?が付いていなくてもnullを受け付けるpublic classTextWriter{public virtual string NewLine{get;[AllowNull] set;}}例: TextWrite.NewLine (System.IO)setだけnullable(nullを渡すとEnvironment.NewLineに置き換える仕様)var t = new StreamWriter(path);Console.WriteLine(t.NewLine.Length);t.NewLine = null;getはnot nullsetはnullを渡しても平気
47.
DisallowNull• ?が付いていてもnullを受け付けないpublic interfaceIEqualityComparer<in T>{bool Equals([AllowNull] T x, [AllowNull] T y);int GetHashCode([DisallowNull] T obj);}例: IEqualityComparer (System.Collections.Generic)同じ型引数に対してメソッドごとにnull許容性が違うvar c = EqualityComparer<string>.Default;c.Equals("", null);var h = c.GetHashCode(null); これはOKこっちは警告
48.
MaybeNull• ?が付いていなくてもnullを返すことがあるpublic classArray{[return: MaybeNull]public static T Find<T>(T[] array, Predicate<T> match);}例: Array.Find (System)条件を満たす要素がなかったらdefaultを返すvar array = new[] { "a", "bc" };var s = Array.Find<string>(array, s => s.Length == 3);Console.WriteLine(s.Length);型はstring (not null)でもnullがあり得る(警告)