Pepek1995
Pepek1995

Reputation: 19

C# Function Pointer / Delegate as a Class Field

I've watched some tutorials and manual pages how to work with delegates but I have still no clue... I have a class and I need every instance of it to have assigned different method Let's say something like:

public Class Shape{
   public void CalculateArea();
}

And then somewhere after declaring Shape RandomShape; set RandomShape.CalculateArea = MethodToCalcThisShapeArea;

The problem is the exact thing I've just written here doesn't compile because methods in classes must have declared body

So i tried

public Class Shape{
   public delegate void CalculateArea();
}

But this acts like a static field – I cannot access it from each class instance but only through the class itself So my last try was

public Class Shape{
   public Action CalculateArea;
}

Which should be the same (i think) since Action is just delegate void but in this case I am able to access it from every instance which sounds great but I am still not able to assign it any method because void cannot be implicitly converted to System.Action

Upvotes: 0

Views: 203

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062770

The line public delegate void CalculateArea(); declares a type, not a per-instance field; you could have, for example:

public class Shape{
   public delegate void MyDelegateType();
   public MyDelegateType CalculateArea;
}

which would declare a type and a per-instance field of that type, but a: you'd probably just want to use Action, and b: you'd usually use either a property or an event here:

public class Shape{
   public event Action CalculateArea;
}

I also wonder whether an abstract method might be more what you're after here:

public abstract class Shape{
   public abstract void CalculateArea();
}

Upvotes: 3

Related Questions