Created
December 8, 2021 23:28
-
-
Save madmonkey/66c55ed6337af8413281fb91a6c994b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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