-
Notifications
You must be signed in to change notification settings - Fork 1
String Coercion
The per-property comparison routine in this library is quite flexible. This flexibility is partly achieved by String Coercion. String Coercion is the process of converting a property value from whatever its type to a string by calling the ToString() method of the property values. This happens automatically if properties matched for comparison differ in their return data type. It also may happen on demand if a property map exists that explicitly request string coercion.
Whenever string coercion happens, it happens before attempting to compare the property values. This means that, whenever string coercion happens, the string IComparer is used and the Result property of the corresponding PropertyComparisonResult object is combined with the ComparisonResult.StringCoercion enumeration value. To understand fully the value in the PropertyComparisonResult.Result property see The Result Property section.
To forcefully convert property values to string before comparison, attributed configuration, fluent interface type configuration or fluent interface comparer configuration can be used. It is achieved by defining a property map specially configured for this task.
//Using attributed configuration:
public class PurchaseOrder
{
//For comparison of purchase orders with purchase orders.
[PropertyMap(typeof(PurchaseOrder), PropertyMapOperation.MapToProperty, nameof(OrderDate),
ForceStringValue = true, FormatString = "yyyyMMdd", TargetFormatString = "yyyyMMdd")]
public DateTime OrderDate { get; set; }
}
//Using fluent interface type configuration:
Scanner.ConfigureType<PurchaseOrder>().ForType<PurchaseOrder>()
.MapProperty(src => src.OrderDate, dst => dst.OrderDate, true, "yyyyMMdd", "yyyyMMdd");
//Using fluent interface comparer configuration:
ObjectComparer oc = ComparerConfigurator.Configure<PurchaseOrder>()
.MapProperty(src => src.OrderDate, dst => dst.OrderDate, true, "yyyyMMdd", "yyyyMMdd")
.CreateComparer();The strings "yyyyMMdd" are format strings: One for the source property value and one for the target property value. They are optional and only work for property return types that implement the IFormattable interface, such as the DateTime data type. The use of format strings come in handy for "similar" data types as they can be used to "standardize" the output.
NOTE: String coercion of values can catch exceptions thrown during the process. If this happens, the exception will be collected and the PropertyComparisonResult.Result property value will note the fact appropriately.