Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active June 16, 2020 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsscoder/bac9f56d45c3835e617006b9eb368817 to your computer and use it in GitHub Desktop.
Save gsscoder/bac9f56d45c3835e617006b9eb368817 to your computer and use it in GitHub Desktop.
Simple C# extension method to serialize an object to a dictionary
using System.Collections.Generic;
public static class ObjectExtensions {
public static IDictionary<string, string> ToDictionary(this object obj) =>
ToDictionary<string>(obj);
public static IDictionary<string, T> ToDictionary<T>(this object obj)
{
var properties = obj.GetType().GetProperties();
var result = new Dictionary<string, T>(capacity: properties.Length);
foreach (var property in properties) {
result[property.Name] = (T)property.GetValue(obj);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment