I have created a modelbinder using reflection to set property values from a csv file. All values parsed from the file are strings. I am using Convert.ChangeType
which has worked for most cases to convert to relevant types i.e. int, long etc. but now a value "20180227" for a date needs to be parsed to my DateTime
property. The format in the csv is yyyyMMdd. The code I have so far:
foreach (var property in matchedModel)
{
Type propType = Nullable.GetUnderlyingType(property.Value.PropertyType) ??
property.Value.PropertyType;
var value = string.IsNullOrEmpty(data.Value[property.Key]) ? null :
Convert.ChangeType(data.Value[property.Key], propType);
property.Value.SetValue(instance, value, null);
}
data.Value[property.Key]
is what holds my parsed string.
The property
variable is the relevant property that needs to be set. Since I had some nullable properties I had to use the Nullable.GetUnderlyingType
.
The problem is that Convert.ChangeType
can't infer how to properly change my date format into a DateTime object. What I could do is something like:
if(property is datetime) do value conversion
However this would be too hardcoded and I want something more generic/dynamic. What would be the best way to approach this?