I have a process that allows users to upload data in Excel file and save to database once the data have gone series of validations . Once such validation is data type validation, to prevent them trying to put a string into integer field, for example. Here is an excerpt of the code. The caller (ValidateContentDataType) calls ValidateDataType() and passes property info and data in string to the callee to perform TryParse.
public void ValidateContentDataType()
{
//Do stuff
ValidateDataType(typeof(T).GetProperty("nameOfProperty"), data);
//Do stuff
}
private bool ValidateDataType(PropertyInfo propInfo, string dataElement)
{
if (propInfo is null) return true;
if (propInfo.PropertyType == typeof(decimal) || propInfo.PropertyType == typeof(decimal?))
{
return decimal.TryParse(dataElement, out decimal temp);
}
//Other ifs TryParse for different data type....
return true;
}
While this works, I don't like the series of ifs in ValidateDataType(). Instead of series of ifs for different data types, like this:
if (propInfo.PropertyType == typeof(decimal) || propInfo.PropertyType == typeof(decimal?))
{
return decimal.TryParse(dataElement, out decimal temp);
}
is it possible to have something like this:
return *propertyType*.TryParse(dataElement, out *propertyType *temp);
Stylistically, I'd probably write that as a
switchstatement:I think that looks a lot better than multiple
ifstatements. But I freely admit that it's a subjective opinion.There might be a solution that involves creating a generic method that expects a type that implements the IParseable interface. Something like:
But I haven't completely worked it out. Might be that you'd have to call the method through reflection.