Null Checking Patterns
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 33/66。
Nullチェックは、堅牢なC#コードを書くために不可欠な要素です。null値を安全にチェックするために使用できるパターンがいくつかあります。
一般的なnullチェックのパターンをいくつか見ていきましょう:
まず、基本的な if-null チェックです:
string name = null;
if (name == null)
{
Console.WriteLine("Name is null");
}
もう一つの一般的なパターンは、null条件演算子(?.)です。これは、nullである可能性があるオブジェクトのメンバーに安全にアクセスします:
string name = null;
int? length = name?.Length; // lengthはnullになります
null合体演算子 (??) は、式がnullの場合にデフォルト値を提供します。
string name = null;
string displayName = name ?? "Unknown"; // displayName は "Unknown" になります
より複雑なシナリオのために、これらのパターンを組み合わせることもできます:
string name = null;
int length = (name ?? "").Length; // lengthは0になります
string.IsNullOrWhiteSpace() メソッドは、文字列が null、空、または空白文字のみで構成されているかどうかを、1 回の呼び出しで確認できる便利な方法です。
string name = null;
if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Name is null, empty, or whitespace");
}
これは、null、空の文字列、および空白のみの文字列を同じように扱う必要がある場合に特に便利です。例えば:
string name1 = null;
string name2 = "";
string name3 = " ";
// 3つすべてがメッセージを出力します
if (string.IsNullOrWhiteSpace(name1)) Console.WriteLine("name1 is null/empty/whitespace");
if (string.IsNullOrWhiteSpace(name2)) Console.WriteLine("name2 is null/empty/whitespace");
if (string.IsNullOrWhiteSpace(name3)) Console.WriteLine("name3 is null/empty/whitespace");
string.IsNullOrWhiteSpace() は単純な null チェックとは異なることに注意してください。これは、空の文字列や、スペース、タブ、その他の空白文字のみを含む文字列も検出します。
チャレンジ
簡単userName という文字列パラメータを受け取る processUserName というメソッドを作成してください。このメソッドは以下を行う必要があります:
userNameが null の場合、"No user provided" を返しますuserNameが空、または空白のみの場合、"Invalid username" を返します- それ以外の場合は、"Welcome, [userName]!" を返します([userName] は実際のユーザー名です)
適切な 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