Earn More by Sharing What You Love
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!
[[academy-video-youtube({"vid":"eOpmjGF4qxo", "start_time":"0", "title":"C#ヌル条件演算子(? オペレーター)の説明!", "creator": "Gerald Versluis", "length": "13分26秒"})]]
ジェラルド・ヴァースルイスは、あるビデオの中で、サンプルコードのクエスチョンマーク(? そのため、C#のnull-conditional演算子を説明する詳細なビデオを作成しました。 もし?[ ]がC#で何をするのか疑問に思ったことがあるならば、Geraldのビデオはそれを明確に理解するための素晴らしいリソースです。 それでは、彼の説明を順を追って見ていきましょう。
Geraldは、メンバーアクセス演算子と式に関するMicrosoftの公式文書を参照することから始めます。 彼は、C# 6で導入されたNULL条件演算子に関するセクションに注目しています。収録時点では、C# 9が最新バージョンで、C# 10も視野に入っている。
Geraldはaがnullの場合は、式全体がNullReferenceExceptionをスローするのではなく、nullとして評価されることを説明します。 そうでなければ、普通に値を取得します。
ドキュメントは役に立ちますが、ジェラルドは実践的な例を好むので、インタラクティブなコーディング環境に移行します。
デモンストレーションのために、ジェラルドは対話型の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 Property Name As String
' A reference to another Person object representing the partner
Public Property Partner As Person
' An array representing the Person's hobbies
Public Property Hobbies As String()
End Class彼は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 Nothing
Dim person As Person = Nothing
' Attempting to access a property of a Nothing 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 IsNot Nothing Then
Console.WriteLine(person.Name)
End Ifこれは有効ですが、余分なコード行が発生します。 ジェラルドは、ヌル条件演算子がどのようにこれを単純化するかを説明します:
// 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を返すだけで、クラッシュしません。
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
Dim person As New Person With {.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となり、ランタイムエラーを防ぎます。
ジェラルドは、配列とコレクションまで議論を広げます。 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(If(person?.Hobbies?.ElementAtOrDefault(0), Nothing))ここでは、Hobbiesがnullだと、式は例外を引き起こすのではなく、nullとして評価されます。
ジェラルドのビデオでは、C#のNULL条件演算子について詳しく説明しています。 ?[ ]を利用することで、開発者はNullReferenceExceptionを回避し、よりクリーンで安全なコードを書くことができます。 プロパティ、ネストされたオブジェクト、配列のいずれを扱う場合でも、NULL条件演算子はコードをより簡潔で読みやすくします。
完全なデモンストレーションについては、Gerald Versluis のビデオをぜひご覧ください!
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!
Join our newsletter, you’ll get exclusive access on article updates. We value your privacy