Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a method that accepts 2 objects of the same Type, a property, and compares the values

Tags:

c#

compare

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

like image 315
TheGeneral Avatar asked Dec 18 '14 22:12

TheGeneral


Video Answer


1 Answers

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.

like image 113
Reed Copsey Avatar answered Sep 28 '22 03:09

Reed Copsey