Skip to content

Instantly share code, notes, and snippets.

@flpinheiro
Last active September 27, 2022 02:40
Show Gist options
  • Select an option

  • Save flpinheiro/07912ae4b6b5f2edf9fba03b17e39bb2 to your computer and use it in GitHub Desktop.

Select an option

Save flpinheiro/07912ae4b6b5f2edf9fba03b17e39bb2 to your computer and use it in GitHub Desktop.
9bject extension to create dictionary from object and vice versa
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class ObjectExtensions
{
public static T ToObject<T>(this IDictionary<string, object> source)
where T : class, new()
{
var someObject = new T();
var someObjectType = someObject.GetType();
foreach (var item in source)
{
someObjectType
.GetProperty(item.Key)
.SetValue(someObject, item.Value, null);
}
return someObject;
}
public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
{
return source.GetType().GetProperties(bindingAttr).ToDictionary
(
propInfo => propInfo.Name,
propInfo => propInfo.GetValue(source, null)
);
}
}
class A
{
public string Prop1
{
get;
set;
}
public int Prop2
{
get;
set;
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Prop1", "hello world!");
dictionary.Add("Prop2", 3893);
A someObject = dictionary.ToObject<A>();
IDictionary<string, object> objectBackToDictionary = someObject.AsDictionary();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment