Null Checking Patterns
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 33/66。
Null チェックは、堅牢な C# コードを書く上で不可欠な部分です。null 値を安全にチェックするためのいくつかのパターンがあります。
いくつかの一般的な null チェックのパターンを探求してみましょう:
まず、基本的な null チェック:
string name = null;
if (name == null)
{
Console.WriteLine("Name is null");
}
もう一つの一般的なパターンは null 条件付き演算子(?.)で、潜在的に null なオブジェクトのメンバーを安全にアクセスします:
string name = null;
int? length = name?.Length; // length will be null
null 合体演算子(??)は、式が null の場合にデフォルト値を提供します:
string name = null;
string displayName = name ?? "Unknown"; // displayName will be "Unknown"
これらのパターンを連結して、より複雑なシナリオにも対応できます:
string name = null;
int length = (name ?? "").Length; // length will be 0
string.IsNullOrWhiteSpace() メソッドは、文字列が null、空、または空白文字のみを含むかどうかをチェックします。これは、1回の呼び出しで文字列入力を検証する便利な方法です:
string name = null;
if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("No name provided"); // this will print
}
string blank = " ";
if (string.IsNullOrWhiteSpace(blank))
{
Console.WriteLine("Blank name provided"); // this will also print
}
string.IsNullOrWhiteSpace() は、null、空の文字列、空白のみの文字列を同等の無効な入力として扱いたい場合に使用します。
チャレンジ
簡単processUserName という名前のメソッドを作成してください。このメソッドは文字列パラメータ userName を受け取ります。メソッドは以下を行うべきです:
userNameが null の場合、"No user provided" を返しますuserNameが空または空白のみの場合、"Invalid username" を返します- それ以外の場合、"Welcome, [userName]!" を返します。ここで [userName] は実際のユーザー名です
適切な null チェックのパターンを使用することをお忘れなく。
チートシート
== null を基本的な null チェックに使用します:
if (name == null)
{
Console.WriteLine("Name is null");
}メンバーに安全にアクセスするために null 条件演算子 ?. を使用します:
int? length = name?.Length; // length will be null if name is nullデフォルト値を指定するために null 結合演算子 ?? を使用します:
string displayName = name ?? "Unknown";null、空、または空白のみの文字列をチェックするために string.IsNullOrWhiteSpace() を使用します:
if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Name is null, empty, or whitespace");
}複雑なシナリオで演算子をチェーンします:
int length = (name ?? "").Length; // length will be 0 if name is null自分で試してみよう
using System;
class ProcessUserName
{
public static string processUserName(string userName)
{
// ここにコードを書いてください
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety