null条件演算子(?.)は、C# 6.0で導入された機能で、オブジェクトがnullでない場合にのみメンバーにアクセスするための簡潔な方法を提供します。
注意点:
型の変化:
値型に対してnull条件演算子を使用すると、結果はnull許容型になります。
// Null条件演算子 (?.) の解説
// 1. 基本的な使い方
string name = person?.Name;
// 上記は以下と同等:
// string name = (person != null) ? person.Name : null;
// 2. メソッド呼び出し
int? length = name?.Length;
// 上記は以下と同等:
// int? length = (name != null) ? (int?)name.Length : null;
// 3. インデクサーとの組み合わせ
char? firstChar = name?[0];
// 上記は以下と同等:
// char? firstChar = (name != null && name.Length > 0) ? (char?)name[0] : null;
// 4. メソッドチェーン
string upperName = person?.Name?.ToUpper();
// 上記は以下と同等:
// string upperName = (person != null) ? (person.Name != null ? person.Name.ToUpper() : null) : null;
// 5. Null合体演算子との組み合わせ
string displayName = person?.Name ?? "Unknown";
// 上記は以下と同等:
// string displayName = (person != null && person.Name != null) ? person.Name : "Unknown";
// 6. コレクションとの使用
int? firstItem = myList?.FirstOrDefault();
// 上記は以下と同等:
// int? firstItem = (myList != null) ? myList.FirstOrDefault() : null;
// 7. デリゲートの呼び出し
myDelegate?.Invoke();
// 上記は以下と同等:
// if (myDelegate != null) myDelegate.Invoke();
// 8. 条件付きアクセス
bool isAdmin = user?.Roles?.Contains("Admin") ?? false;
// 上記は以下と同等:
// bool isAdmin = (user != null && user.Roles != null) ? user.Roles.Contains("Admin") : false;