Close this search box.

Convert Dynamic to Type and convert Type to Dynamic

public static class DynamicExtensions {
  public static T FromDynamic<T>(this IDictionary<string, object> dictionary) {
    var bindings = new List<MemberBinding>();
    foreach (var sourceProperty in typeof(T).GetProperties().Where(
                 x => x.CanWrite)) {
      var key = dictionary.Keys.SingleOrDefault(
          x => x.Equals(sourceProperty.Name,
      if (string.IsNullOrEmpty(key))
      var propertyValue = dictionary[key];
          Expression.Bind(sourceProperty, Expression.Constant(propertyValue)));
    Expression memberInit =
        Expression.MemberInit(Expression.New(typeof(T)), bindings);
    return Expression.Lambda<Func<T>>(memberInit).Compile().Invoke();

  public static dynamic ToDynamic<T>(this T obj) {
    IDictionary<string, object> expando = new ExpandoObject();

    foreach (var propertyInfo in typeof(T).GetProperties()) {
      var propertyExpression =
          Expression.Property(Expression.Constant(obj), propertyInfo);
      var currentValue = Expression.Lambda<Func<string>>(propertyExpression)
      expando.Add(propertyInfo.Name.ToLower(), currentValue);
    return expando as ExpandoObject;

posted on Saturday, June 02, 2012 8:10 PM

This article is part of the GWB Archives. Original Author: JonCanning

Related Posts