Skip to main content

C# extension method to convert an object into a Dictionary type; using the property names as keys, and property values as each key value.

internal static class ObjectExtensions
{
    public static IDictionary<string, object> ToDictionary(this object @object)
    {
        var dictionary = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);

        if (@object != null)
        {
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(@object))
            {
                dictionary.Add(property.Name, property.GetValue(@object));
            }
        }

        return dictionary;
    }
}

//
// Example Usage:
// ----------------------------------------------------------------------------

internal class Person
{
    public string FirstName { get; set; }
    public string LastName {get; set; }
}

internal class Program
{
    private static void Main(string[] args)
    {
        var person = new Person { FirstName = "Jon", LastName = "LaBelle" };
        var dictionary = person.ToDictionary();

        foreach (var item in dictionary)
        {
            Console.WriteLine("{0}: {1}", item.Key, item.Value);
        }

        // Outputs...
        // FirstName: Jon
        // LastName: LaBelle
    }
}