Last active
June 16, 2020 09:52
-
-
Save gsscoder/bac9f56d45c3835e617006b9eb368817 to your computer and use it in GitHub Desktop.
Simple C# extension method to serialize an object to a dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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