When creating request parameters for an API or outputting logs, you may often want to convert a class or anonymous type object into “property name” and “value” pairs (key-value format).
By using Reflection, you can create a generic conversion method that does not depend on specific type definitions. In this article, I will explain an implementation example that converts an arbitrary object into a Dictionary<string, string>.
Table of Contents
- Implementation Sample: PC Spec Info Dictionary Conversion
- Sample Code
- Execution Result
- Explanation and Technical Points
- GetProperties Method
- GetValue Method
- Uses and Applications
Implementation Sample: PC Spec Info Dictionary Conversion
The following code converts a class (or anonymous type) containing PC specification information into a dictionary where property names act as keys. It then outputs the result to the console.
Sample Code
using System;
using System.Collections.Generic;
using System.Reflection;
public class Program
{
public static void Main()
{
// 1. Source data (can be an anonymous type or a class)
var gamingPc = new
{
Model = "Alienware X15",
Cpu = "Core i9-12900H",
RamGB = 32,
SsdTB = 1.0,
IsLaptop = true
};
// 2. Convert object to Dictionary
Dictionary<string, string> specSheet = ObjectToDictionary(gamingPc);
// 3. Display results
Console.WriteLine("--- Spec List ---");
foreach (var item in specSheet)
{
Console.WriteLine($"{item.Key, -10}: {item.Value}");
}
}
/// <summary>
/// Converts public properties of an arbitrary object into a dictionary
/// </summary>
/// <param name="data">The object to convert</param>
/// <returns>Key: Property Name, Value: Property Value (String)</returns>
public static Dictionary<string, string> ObjectToDictionary<T>(T data)
{
// Dictionary to store the result
var dict = new Dictionary<string, string>();
if (data == null) return dict;
// Get type information
Type type = typeof(T);
// Get all public instance properties
PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var prop in properties)
{
// Get the value of the property
object value = prop.GetValue(data);
// If value is null, use empty string; otherwise convert to string
// Use property name as the dictionary key
dict[prop.Name] = value?.ToString() ?? string.Empty;
}
return dict;
}
}
Execution Result
--- Spec List ---
Model : Alienware X15
Cpu : Core i9-12900H
RamGB : 32
SsdTB : 1
IsLaptop : True
Explanation and Technical Points
1. GetProperties Method
By calling typeof(T).GetProperties(), you can retrieve a list (an array of PropertyInfo) of all public properties that the type possesses. This allows for dynamic processing, even when you do not know beforehand what properties the object has.
2. GetValue Method
Using the GetValue(obj) method of the retrieved PropertyInfo object allows you to extract the actual value of that property from a specific instance.
3. Uses and Applications
This technique is very useful in the following scenarios:
- HTTP Requests: Converting objects into pairs for
FormUrlEncodedContent. - Log Output: Breaking down objects into flat key-value pairs for structured logging.
- Configuration Files: Converting the format of class settings before writing them to a file.
If you want to handle values in their original types instead of converting them to strings, you can simply change the return type to Dictionary<string, object>.
