Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set property value of nullable datetime

Try to update a specific property of my model with Reflection. This works for all other types of my model except properties of type DateTime?

Code:

public void UpdateProperty(Guid topicGuid, string property, string value)
{
    var topic = Read(topicGuid);
    PropertyInfo propertyInfo = topic.GetType().GetProperty(property);
    propertyInfo.SetValue(topic, Convert.ChangeType(value, propertyInfo.PropertyType), null);

    topic.DateModified = DateTime.Now;

    Save();
}

The following error is thrown on the Convert.ChangeType part:

Invalid cast from 'System.String' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'

How can this be solved?

Update

Got it working with Daniel A. White 's solution

Code updated (probably needs some finetuning, but it works):

public void UpdateProperty(Guid topicGuid, string property, string value)
{
    var topic = Read(topicGuid);

    PropertyInfo propertyInfo = topic.GetType().GetProperty(property);

    object changedType = propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(DateTime?)
            ? DateTime.Parse(value)
            : Convert.ChangeType(value, propertyInfo.PropertyType);

    propertyInfo.SetValue(topic, changedType, null);

    topic.DateModified = DateTime.Now;

    Save();
}
like image 256
Dairo Avatar asked Jan 02 '15 15:01

Dairo


People also ask

Can DateTime be nullable?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

How do I assign a null value to a DateTime variable in C#?

The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.

Can date data type be null?

Yes. If you have a nullable datetime column, then its fine.


1 Answers

Try to replace

Convert.ChangeType(value, propertyInfo.PropertyType)

by

Convert.ChangeType(value, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType)

(Not tested)

like image 196
schglurps Avatar answered Oct 18 '22 00:10

schglurps