using System.Collections.Generic;
using System.ComponentModel;
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public string Street { get; set; }
public int PostalCode { get; set; }
public static void Main()
var result = person.ToDictionary();
Console.WriteLine(result);
public static class ObjectToDictionaryHelper
public static IDictionary<string, object> ToDictionary(this object source)
return source.ToDictionary<object>();
public static IDictionary<string, T> ToDictionary<T>(this object source)
ThrowExceptionWhenSourceArgumentIsNull();
var dictionary = new Dictionary<string, T>();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
AddPropertyToDictionary<T>(property, source, dictionary);
private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, IDictionary<string, T> dictionary)
var value = property.GetValue(source);
dictionary.Add(property.Name, (T)value);
private static bool IsOfType<T>(object value)
private static void ThrowExceptionWhenSourceArgumentIsNull()
throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");