Skip to main content

Converts any object to a dictionary.

using System;
using System.ComponentModel;
using System.Collections.Generic;

public static class ObjectExtensions
{
    /// <summary>
    /// Convert the object properties to a dictionary
    /// </summary>
    /// <param name="self"></param>
    /// <returns></returns>
    public static IDictionary<string, object> ToDictionary(this object self)
    {
        return self.ToDictionary<object>();
    }

    /// <summary>
    /// Converts the object properties to a dictionary
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="self"></param>
    /// <returns></returns>
    public static IDictionary<string, T> ToDictionary<T>(this object self)
    {
        if (self == null)
        {
            ThrowExceptionWhenSourceArgumentIsNull();
        }

        var dictionary = new Dictionary<string, T>();
        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(self))
        {
            AddPropertyToDictionary<T>(property, self, dictionary);
        }

        return dictionary;
    }

    private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object self, Dictionary<string, T> dictionary)
    {
        object value = property.GetValue(self);
        if (IsOfType<T>(value))
        {
            dictionary.Add(property.Name, (T)value);
        }
        else
        {
            T newValue = (T)Convert.ChangeType(value, typeof(T));
            dictionary.Add(property.Name, newValue);
        }
    }

    private static bool IsOfType<T>(object value)
    {
        return value is T;
    }

    private static void ThrowExceptionWhenSourceArgumentIsNull()
    {
        throw new ArgumentNullException("self", "Unable to convert object to a dictionary. The source object is null.");
    }
}

class MyClass
{
    public MyClass()
    {
        MyProperty = "Value 1";
        MyProperty2 = "Value 2";
        MyInt = 2;
    }

    public string MyProperty
    {
        get;
        set;
    }
    public string MyProperty2
    {
        get;
        set;
    }
    public int MyInt
    {
        get;
        set;
    }
}

// Usage:
class Program
{
    static void Main(string[] args)
    {
        MyClass _Object = new MyClass();
        IDictionary<string, string> dic = _Object.ToDictionary<string>();
        foreach (var val in dic)
        {
            Console.WriteLine(val);
        }
    }
}