Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Setting object DateTime property values through reflection

I want to set all DateTime properties of my object to a default date. However, if I try do set the values through reflection I get the exception: "Object does not match target type."

private void SetDefaultValues()
{
    DateTime dt = DateTime.Parse("1/1/2000", new CultureInfo("en-US", true));
    foreach (PropertyInfo p in this.GetType().GetProperties())
    {
        if (p.PropertyType.FullName == "System.DateTime")
        {                                      
            p.SetValue(dt, typeof(DateTime), null);
        }
    }
}

Am I doing / thinking something fundamentally incorrect?

like image 958
Mike Avatar asked Nov 02 '11 22:11

Mike


1 Answers

Parameters need adjusting; the first is the target - which I assume is this here; the second is the value (dt). The last relates to "indexers" - which probably doesn't apply here.

p.SetValue(this, dt, null);
like image 174
Marc Gravell Avatar answered Oct 05 '22 12:10

Marc Gravell