[C#] Batch Convert All Null String Properties to Empty Strings

When saving data to a database or returning data as an API response, you may want to unify all null string properties to empty strings ("").

If there are only a few properties, you can manually write if (str == null) str = "";. However, when there are many properties or multiple target classes, it is more efficient to create a generic conversion method using Reflection.

目次

Table of Contents

  • Implementation of Replacing Null with Empty String
  • Sample Code
  • Execution Result
  • Explanation and Technical Points
    1. Property Filtering
    2. SetValue Method
    3. Note on Recursive Processing

Implementation of Replacing Null with Empty String

The following sample code detects null string properties in a Customer class and automatically rewrites them to empty strings.

Sample Code

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        // 1. Create test data (leave some properties as null)
        var customer = new Customer
        {
            Id = 101,
            LastName = "Sato",
            // FirstName is null
            // Address is null
            // Note is null
        };

        Console.WriteLine("--- Before Conversion ---");
        PrintProperties(customer);

        // 2. Batch convert null string properties to empty strings
        ReplaceNullWithEmptyString(customer);

        Console.WriteLine("\n--- After Conversion ---");
        PrintProperties(customer);
        
        // Verification: Check if they are truly empty strings
        if (customer.FirstName == "" && customer.Address == "" && customer.Note == "")
        {
            Console.WriteLine("\n[Success] All null properties were replaced with empty strings.");
        }
    }

    /// <summary>
    /// Scans string properties in an object and sets them to empty string if null
    /// </summary>
    public static void ReplaceNullWithEmptyString<T>(T obj)
    {
        if (obj == null) return;

        Type type = typeof(T);

        // Get Public and Instance (non-static) properties
        var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var prop in properties)
        {
            // 1. Skip non-string types
            if (prop.PropertyType != typeof(string))
            {
                continue;
            }

            // 2. Skip properties that cannot be written to (no setter)
            if (!prop.CanWrite)
            {
                continue;
            }

            // 3. Get current value and check if null
            var currentValue = prop.GetValue(obj);
            if (currentValue == null)
            {
                // 4. If null, set to empty string
                prop.SetValue(obj, string.Empty);
            }
        }
    }

    // Method to display properties for verification
    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)"}");
    }
}

// Customer Class
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; }
}

Execution Result

--- Before Conversion ---
Name: Sato (null)
Addr: (null)
Note: (null)

--- After Conversion ---
Name: Sato 
Addr: 
Note: 

[Success] All null properties were replaced with empty strings.

Explanation and Technical Points

1. Property Filtering

We filter the list of properties obtained by type.GetProperties() to narrow down the target:

  • prop.PropertyType == typeof(string): Targets only string types.
  • prop.CanWrite: We check this to exclude read-only properties (properties without a set accessor), as attempting to write to them would cause an error.

2. SetValue Method

We use prop.SetValue(obj, value) to dynamically rewrite the property value of the object. In this example, we set it to string.Empty (or ""), but this logic can also be applied to reverse operations, such as “converting empty strings to null.”

3. Note on Recursive Processing

The code above only targets top-level properties. If you have nested objects (e.g., a property that contains another class with its own string properties), you would need to add logic to check if a property is a class and call the method recursively.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次