Convert object to dynamic

February 6, 2022 ยท View on GitHub

When you want an object that is not dynamic to take on dynamic capabilities, this extension method is your friend:

//Using System.Dynamic and System.ComponentModel
public static class Extensions
{
	public static dynamic ToDynamic(this object value)
	{
		if (value.IsListOrArray())
		{

			var list = new List<ExpandoObject>();
			IEnumerable enumerable = value as IEnumerable;
			foreach (object o in enumerable)
			{
				list.Add(o.ToDynamic());
			}

			return (dynamic)list;
		}

		IDictionary<string, object> expando = new ExpandoObject();

		foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
		{
			expando.Add(property.Name, property.GetValue(value));
		}

		return (dynamic)expando;
	}

	public static bool IsListOrArray(this object value)
	{
		if (value is IList && value.GetType().IsGenericType)
		{
			return true;
		}

		var valueType = value.GetType();
		if (valueType.IsArray)
		{
			return true;
		}

		return false;
	}
}

Source

See also