Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegates and inheritance in c#

I have a bit of a problem with inheritance of delegates. Delegate as far as i understand is a pointer to a pair: an instance and a method, the thing is this is the method referenced in the creation of the delegate, and not affected by inheritance. So, this won't work:

public class BaseObject {
  public delegate void del();

  public BaseObject() {
    next=Method;
  }

  public del next;
  public void ExecuteNext() {
    next();
  }

  public virtual void Method() {
    Debug.Log("BASE");
  }
}

public class InheritedObject:BaseObject {
  override public void Method() {
    Debug.Log("INHERITED");
  }
}
...

(new InheritedObject()).ExecuteNext();

Execute runs the base Method(), I want it to run the inherited Method(). I have found some way around, but it is inefficient, distracting and very error prone, anyway here's the current working version that I'd like to get rid of:

class BaseObject {
  public delegate void del();

  BaseObject() {
    next=DoMethod;     /// using DoMethod here
  }

  public del next;
  public void ExecuteNext() {
    next();
  }


  public void DoMethod() {    /// using DoMethod here
    Method();
  }
  public virtual void Method() {
    // do base
  }
}

class InheritedObject:BaseObject {
  override public void Method() {
    // do inherited
  }
}

...

(new InheritedObject()).Execute();

This DoMethod aproach works but has many problems,

  1. lots of useless code
  2. error prone when using the class - easy to mistake obj.next=DoMethod with obj.next=Method
  3. error prone when inheriting the class - I have to remember to not to inherit the DoMethod, and lots of virtual and overrides.

Any suggestions how can I do that better? Perhaps some annotation magic that does the DoMethod by itself? I've already thought of dictionaries - they aren't good here, they add even another level of confusion (Mono, .NET 2, Unity3d framework)

like image 763
Krzysztof Bociurko Avatar asked Feb 23 '26 06:02

Krzysztof Bociurko


1 Answers

You could replace next=DoMethod; with next= ()=>Method(); which is essentially the same, but doesn't require you to define an extra method on your class.

like image 68
Bubblewrap Avatar answered Feb 25 '26 21:02

Bubblewrap