Skip to content

Instantly share code, notes, and snippets.

@jamescurran
Created December 14, 2023 19:55
Show Gist options
  • Select an option

  • Save jamescurran/2579061be5b5e74257aae8eb5068f26e to your computer and use it in GitHub Desktop.

Select an option

Save jamescurran/2579061be5b5e74257aae8eb5068f26e to your computer and use it in GitHub Desktop.
Update an Object using a dictionary with the properties to change
public static void UpdateFromText<T>(this T target, IDictionary<string, object> changes)
where T : class
{
foreach (var kvp in changes)
{
var propsTarget = typeof(T).GetProperty(kvp.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propsTarget == null)
//throw new ArgumentOutOfRangeException(nameof(changes), $"{kvp.Key} is not a property of the target");
continue;
try
{
var newVal = kvp.Value;
var newStr = newVal as string;
if (newStr == "null" || newVal == null)
{
if (propsTarget.PropertyType.IsClass || IsNullable(propsTarget))
propsTarget.SetValue(target, null);
}
else
{
var targetType = IsNullable(propsTarget)
? propsTarget.PropertyType.GenericTypeArguments[0]
: propsTarget.PropertyType;
if (targetType == typeof(bool))
{
char chr = Char.ToUpperInvariant(newStr[0]);
if (chr == 'Y')
{
propsTarget.SetValue(target, true);
continue;
}
else if (chr == 'N')
{
propsTarget.SetValue(target, false);
continue;
}
}
object value = Convert.ChangeType(newVal, targetType);
propsTarget.SetValue(target, value);
}
}
catch (Exception ex)
{
throw new ArgumentOutOfRangeException(
$"{kvp.Value} is not assignable to {propsTarget.PropertyType.Name} (Property {kvp.Key})", ex);
}
}
}
public static bool IsNullable(PropertyInfo type) =>
type.PropertyType.IsConstructedGenericType && type.PropertyType.Name == "Nullable`1";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment