Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing delegates for equality

I'm building a hierarchical collection class that orders magnetic resonance images spatially and arranges them into groupings based on the various acquisition parameters that were used to generate them. The specific method used to perform the grouping is provided by the user of the class. I've abstracted out the relevant features in the sample code below. For the IEquatable<MyClass> implementation, I'd like to be able to compare the _myHelperDelegate attributes of two MyClass instances to determine if both delegates point to the same piece of code. The (_myHelperDelegate == other._myHelperDelegate) clause in the if statement below is clearly the wrong way to go about doing this (it fails to compile, giving the error "Method name expected"). My question is, is there a way to compare two delegates to determine if they reference the same piece of code? If so, how do you do that?

public class MyClass : IEquatable<MyClass>
{
   public delegate object HelperDelegate(args);
   protected internal HelperDelegate _myHelperDelegate;

   public MyClass(HelperDelegate helper)
   {
      ...
      _myHelperDelegate = helper;
   }

   public bool Equals(MyClass other)
   {
      if (
          (_myHelperDelegate == other._myHelperDelegate) &&
          (... various other comparison criteria for equality of two class instances... )
         )
         return true;
      return false;
   }
}
like image 854
Matt Avatar asked Mar 04 '11 19:03

Matt


1 Answers

The following compiles and works as expected.

private void Form1_Load(object sender, EventArgs e)
{
    var helper1 = new TestDelegates.Form1.MyClass.HelperDelegate(Testing);
    var helper2 = new TestDelegates.Form1.MyClass.HelperDelegate(Testing2);
    var myClass1 = new MyClass(helper1);
    var myClass2 = new MyClass(helper1);

    System.Diagnostics.Debug.Print(myClass1.Equals(myClass2).ToString()); //true

    myClass2 = new MyClass(helper2);
    System.Diagnostics.Debug.Print(myClass1.Equals(myClass2).ToString()); //false

}

private object Testing()
{
    return new object();
}
private object Testing2()
{
    return new object();
}

public class MyClass : IEquatable<MyClass>
{
   public delegate object HelperDelegate();
   protected internal HelperDelegate _myHelperDelegate;

   public MyClass(HelperDelegate helper)
   {
     _myHelperDelegate = helper;
   }

   public bool Equals(MyClass other)
   {
      if (_myHelperDelegate == other._myHelperDelegate)
      {
         return true;
      }
      return false;
   }
}
like image 50
Eric Dahlvang Avatar answered Oct 06 '22 18:10

Eric Dahlvang