Skip to content

Instantly share code, notes, and snippets.

@mgravell
Created August 26, 2021 09:13
Show Gist options
  • Save mgravell/3c88fcd4c57d5a6dd63b781cea07e32a to your computer and use it in GitHub Desktop.
Save mgravell/3c88fcd4c57d5a6dd63b781cea07e32a to your computer and use it in GitHub Desktop.
using System;
using System.Reflection;
public class SomeType
{
static void Main() => new SomeType().DoTheThing();
public void DoTheThing()
{
var prop = GetType().GetProperty(nameof(AgreedInstallationDate));
var value = new DateTime(2021, 08, 17);
UpdateProperty(prop, value);
}
public DateTime? AgreedInstallationDate { get; set; }
private void UpdateProperty(PropertyInfo prop, object newValue)
{
// Align data type
Type propType = prop.PropertyType;
if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
newValue = ChangeTypeEx(newValue, propType);
}
// Store changes back to entity
prop.SetValue(this, newValue);
// Even this doesn't work
prop.SetValue(this, (DateTime?)DateTime.Now);
}
public static object ChangeTypeEx(object obj, Type type)
{
Type targetType = Nullable.GetUnderlyingType(type) ?? type;
if (obj == null)
{
System.Reflection.ConstructorInfo defaultConstructor = targetType.GetConstructor(Type.EmptyTypes);
return defaultConstructor?.Invoke(new object[0]) ?? obj;
}
return Convert.ChangeType(obj, targetType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment