C# object to dictionary

Date: 2020-09-08
public static class ObjectToDictionaryHelper
{
	public static IDictionary<string, T> ToDictionary<T>(object source)
	{
		if (source == null)
			throw new ArgumentNullException("source", "Cannot convert null to a dictionary.");

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

	private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, Dictionary<string, T> dictionary)
	{
		object value = property.GetValue(source);
		if (value is T)
			dictionary.Add(property.Name, (T)value);
	}
}
40180cookie-checkC# object to dictionary