As @IanKemp suggested, you cannot avoid if-check when you want to skip the property assignment. Do not confuse with assigning default value.
The simplest solution is to encapsulate a nullable value check and property assignment into single operation. To avoid passing PropertyInfo
around, you can use the extension method:
public static class ReflectionExtensions
{
public static void SetValueIfNotNull<T>(this PropertyInfo prop, object obj, T? maybe)
where T : struct
{
if (maybe.HasValue)
prop.SetValue(obj, maybe.Value);
}
}
Usage:
myObj.GetType().GetProperty("birthdate").SetValueIfNotNull(myObj, dep.BirthDate);
Or if you work a lot with nullable values and property settings is not the only thing you do, then you can write a nullable extension which will bring your code back to non-nullable path:
public static class NullableExtensions
{
// Note that action has non-nullable argument
public static void Invoke<T>(this Nullable<T> nullable, Action<T> action)
where T: struct
{
if (nullable.HasValue)
action(nullable.Value);
}
}
This approach swaps things around - now you can invoke actions on the value of nullable variable if nullable has value:
dep.BirthDate.Invoke(date => myObj.GetType().GetProperty("birthday").SetValue(myObj, date));
Or even this way if you'll invoke single argument functions
dep.BirthDate.Invoke(myObj.SetProperty<DateTime>("birthday"));