I'm trying to create a helper function (for a class) that accepts 2 objects and compares a property on both classes
These properties are only ever simple types like string
, int
and bool
Usage
Compare(widget1,widget2,x => x.Name)
What i have so far
private void CompareValue<T>(Order target, Order source, Func<Order, T> selector)
{
if(target.selector != source.selector)
{
// do some stuff here
}
}
Obviously the code above doesn't work
You can add a constraint to IEquatable<T>
:
private void CompareValue<T>(Order target, Order source, Func<Order, T> selector)
where T : IEquatable<T>
{
if (!selector(target).Equals(selector(source))
{
// ... Do your stuff
}
}
This would handle the types you specified (as well as many others), and allow the compiler protect you from use cases where this would likely be inappropriate.
Note that you also need to call the Func<T,U>
, ie: selector(target)
and selector(source)
, to create the resulting value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With