C# ヌル条件演算子
ジェラルド・ヴァースルイスは、あるビデオの中で、サンプルコードのクエスチョンマーク(? そのため、C#のnull-conditional演算子を説明する詳細なビデオを作成しました。 C#で?[ ]が何をするのか疑問に思ったことがあるなら、Geraldのビデオはそれを明確に理解するための素晴らしいリソースです。 それでは、彼の説明を順を追って見ていきましょう。
ドキュメント ページによる簡単な説明
Geraldは、メンバーアクセス演算子と式に関するMicrosoftの公式文書を参照することから始めます。 彼は、C# 6で導入されたNULL条件演算子に関するセクションに注目しています。収録時点では、C# 9が最新バージョンで、C# 10も視野に入っている。
Geraldは、aがnullである場合、全体の式がNullReferenceExceptionを投げる代わりにnullと評価されることを説明します。 そうでなければ、普通に値を取得します。
ドキュメントは役に立ちますが、ジェラルドは実践的な例を好むので、インタラクティブなコーディング環境に移行します。
try.dot.netを使用した例
デモンストレーションのために、ジェラルドは対話型のC#環境であるtry.dot.netに切り替えます。 このツールは Blazor 上で動作し、ユーザーはブラウザで直接 C# コードを実行できる。
彼は、try.dot.netにプリロードされているデフォルトのフィボナッチ数列の例を簡単に示し、それをクリアしてヌル条件演算子に焦点を当てた新しい例を開始する。
条件なし演算子の説明
Gerald は、次のプロパティを持つ単純な Person クラスを作成します:
public class Person
{
// The Name property of the Person
public string Name { get; set; }
// A reference to another Person object representing the partner
public Person Partner { get; set; }
// An array representing the Person's hobbies
public string[] Hobbies { get; set; }
}public class Person
{
// The Name property of the Person
public string Name { get; set; }
// A reference to another Person object representing the partner
public Person Partner { get; set; }
// An array representing the Person's hobbies
public string[] Hobbies { get; set; }
}彼はPersonオブジェクトをnullとして初期化します。
// Initialize a Person object as null
Person person = null;
// Attempting to access a property of a null object will throw a NullReferenceException
Console.WriteLine(person.Name);// Initialize a Person object as null
Person person = null;
// Attempting to access a property of a null object will throw a NullReferenceException
Console.WriteLine(person.Name);このコードを実行すると、personがnullのためNullReferenceExceptionがスローされます。 これを防ぐために、開発者は通常、プロパティにアクセスする前にNULLチェックを追加します:
// Check if the person object is not null before accessing its properties
if (person != null)
{
Console.WriteLine(person.Name);
}// Check if the person object is not null before accessing its properties
if (person != null)
{
Console.WriteLine(person.Name);
}これは有効ですが、余分なコード行が発生します。 ジェラルドは、ヌル条件演算子がどのようにこれを単純化するかを説明します:
// Using the null-conditional operator to safely access the Name property
Console.WriteLine(person?.Name);// Using the null-conditional operator to safely access the Name property
Console.WriteLine(person?.Name);今、personがnullの場合、式はクラッシュする代わりに単にnullを返します。
プロパティの Null-Conditional 演算子
GeraldはPersonオブジェクトを設定して例を拡張します。
// Create a new Person object
Person person = new Person { Name = "Gerald" };
// Access the Name property safely
Console.WriteLine(person?.Name);// Create a new Person object
Person person = new Person { Name = "Gerald" };
// Access the Name property safely
Console.WriteLine(person?.Name);personがnullではないので、"Gerald"が正しく出力されます。
次に、入れ子の例を示します:
// Safely access the Name property of the Partner object
Console.WriteLine(person?.Partner?.Name);// Safely access the Name property of the Partner object
Console.WriteLine(person?.Partner?.Name);person.Partnerがnullの場合、式全体が例外を投げる代わりにnullと評価されます。 これにより、不必要なif条件を避けることができます。
ヌル条件演算子を連結する
ジェラルドは、ヌル条件演算子は連鎖させることができ、深く入れ子になったオブジェクトを扱うときにコードをすっきりさせることができると説明しています。 複数のヌルチェックを書く代わりに、以下を使用できます:
// Chain null-conditional operators to safely access nested objects
Console.WriteLine(person?.Partner?.Name);// Chain null-conditional operators to safely access nested objects
Console.WriteLine(person?.Partner?.Name);person.Partnerがnullの場合、結果はnullになり、実行時のエラーを防ぎます。
配列上の Null-Conditional 演算子
ジェラルドは、配列とコレクションまで議論を広げます。 Person クラスに Hobbies 配列を追加し、要素に安全にアクセスする方法を示しています:
// Safely access the first element of the Hobbies array
Console.WriteLine(person?.Hobbies?[0]);// Safely access the first element of the Hobbies array
Console.WriteLine(person?.Hobbies?[0]);ここで、Hobbiesがnullの場合、式は例外を引き起こす代わりにnullと評価されます。
結論
ジェラルドのビデオでは、C#のNULL条件演算子について詳しく説明しています。 ?[ ]を使用することで、開発者はNullReferenceExceptionを回避するよりクリーンで安全なコードを書くことができます。 プロパティ、ネストされたオブジェクト、配列のいずれを扱う場合でも、NULL条件演算子はコードをより簡潔で読みやすくします。
完全なデモンストレーションについては、Gerald Versluis のビデオをぜひご覧ください!

