Skip to content

Instantly share code, notes, and snippets.

@madmonkey
Created December 8, 2021 23:28
Show Gist options
  • Save madmonkey/66c55ed6337af8413281fb91a6c994b3 to your computer and use it in GitHub Desktop.
Save madmonkey/66c55ed6337af8413281fb91a6c994b3 to your computer and use it in GitHub Desktop.
static class TypeExtensions
{
public static bool HasProperty(this Type obj, string propertyName)
{
// ignore case and replace additional default binding parameters
return obj.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) != null;
}
public static bool TrySetProperty<TValue>(this object obj, string propertyName, TValue value)
{
var property = obj.GetType().GetProperty(propertyName,
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (property != null)
{
var propertyType = property.PropertyType;
try
{
//use the converter to get the correct value
property.SetValue(obj, Convert.ChangeType(value, propertyType), null);
return true;
}
catch (Exception ex)
{
//in case of incorrect entry (string to number, etc) - use default values and continue
Trace.WriteLine($"Unable to assign {propertyName} = {value} : {ex.Message}");
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment