====== 114 NULLチェックの回避方法 ====== **「NullReferenceException」**をできるだけ回避する手段を列挙。 ===== nullになりうる変数は事前に初期化しておく ===== Action fugaAction = delegate{}; string hogeText = string.Empty; List hogelist = new List(); Dictionary fooDictionary = new Dictionary(); 宣言と同時に初期化しておけばインスタンスが無いなんてことは無くなるためおすすめ。 \\ \\ ===== 文字列がnullか空かを判断する ===== 通常string型変数の中身がnullか空かを判断するには以下の様に書きます。 if ( str == null || str == "" ) ですが、これではコードが汚くなり保守性が下がるため拡張メソッドを作成します。 public static class StringExtensions { /// /// nullまたは空かを確認します。 /// static public bool IsNullOrEmpty( this string self ) { return string.IsNullOrEmpty(self); } } if ( str.IsNullOrEmpty() ) スッキリします。 \\ \\ ==== ActionやFuncといったデリゲートの場合 ==== if(action != null) { action(); } 毎回nullチェックを入れるのは面倒なので、同様に拡張メソッドを作成。 using System; public static class ActionExtensions { /// /// Action呼び出し。 /// static public void Call( this Action self ) { if(self != null) { self(); } } } action.Call(); nullチェックが不要になります。