データベースへの保存前や、APIレスポンスとしてデータを返す際、文字列プロパティに含まれる null をすべて空文字列("")に統一したい場合があります。
プロパティが数個であれば手動で if (str == null) str = ""; と書けますが、プロパティ数が多い場合や対象クラスが複数ある場合は、リフレクションを使って汎用的な変換メソッドを作るのが効率的です。
目次
nullを空文字に置換する実装
以下のサンプルコードでは、顧客情報(Customer)クラスに含まれる null の文字列プロパティを検出し、自動的に空文字列に書き換える処理を実装しています。
サンプルコード
using System;
using System.Reflection;
public class Program
{
public static void Main()
{
// 1. テストデータ作成(一部のプロパティをnullのままにする)
var customer = new Customer
{
Id = 101,
LastName = "佐藤",
// FirstName は null
// Address は null
// Note は null
};
Console.WriteLine("--- 変換前 ---");
PrintProperties(customer);
// 2. nullの文字列プロパティを一括で空文字に変換
ReplaceNullWithEmptyString(customer);
Console.WriteLine("\n--- 変換後 ---");
PrintProperties(customer);
// 検証: 本当に空文字になっているか確認
if (customer.FirstName == "" && customer.Address == "" && customer.Note == "")
{
Console.WriteLine("\n[成功] すべてのnullプロパティが空文字に置換されました。");
}
}
/// <summary>
/// オブジェクト内のstring型プロパティを走査し、nullがあれば空文字をセットする
/// </summary>
public static void ReplaceNullWithEmptyString<T>(T obj)
{
if (obj == null) return;
Type type = typeof(T);
// PublicかつInstance(staticでない)プロパティを取得
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in properties)
{
// 1. 文字列型以外はスキップ
if (prop.PropertyType != typeof(string))
{
continue;
}
// 2. 書き込み不可(setterがない)プロパティはスキップ
if (!prop.CanWrite)
{
continue;
}
// 3. 現在の値を取得し、nullかどうかチェック
var currentValue = prop.GetValue(obj);
if (currentValue == null)
{
// 4. nullなら空文字列をセット
prop.SetValue(obj, string.Empty);
}
}
}
// 動作確認用の表示メソッド
static void PrintProperties(Customer c)
{
Console.WriteLine($"Name: {c.LastName} {c.FirstName ?? "(null)"}");
Console.WriteLine($"Addr: {c.Address ?? "(null)"}");
Console.WriteLine($"Note: {c.Note ?? "(null)"}");
}
}
// 顧客クラス
public class Customer
{
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Address { get; set; }
public string Note { get; set; }
}
実行結果
--- 変換前 ---
Name: 佐藤 (null)
Addr: (null)
Note: (null)
--- 変換後 ---
Name: 佐藤
Addr:
Note:
[成功] すべてのnullプロパティが空文字に置換されました。
解説と技術的なポイント
1. プロパティのフィルタリング
type.GetProperties() で取得したプロパティ一覧の中から、処理対象を絞り込みます。
prop.PropertyType == typeof(string): 文字列型のみを対象にします。prop.CanWrite:setアクセサが存在しない(読み取り専用)プロパティに値を書き込もうとするとエラーになるため、事前にチェックして除外します。
2. SetValueメソッド
prop.SetValue(obj, value) を使用して、オブジェクトのプロパティ値を動的に書き換えます。 今回は string.Empty(または "")をセットしていますが、逆に「空文字を null に変換する」といった処理にも応用可能です。
3. 再帰処理について
上記のコードはトップレベルのプロパティのみを対象としています。 もし「プロパティの中にさらに別のクラスがあり、その中の文字列も変換したい」という場合(ネストしたオブジェクト)は、プロパティの型がクラスかどうかを判定し、再帰的にメソッドを呼び出すロジックを追加する必要があります。
