ze boris
ze boris

Reputation: 9

Delegate in parameter

I have a bunch of methods that return List of GridTiles, for example GetTopNeighbour. I would like to be able to pass them to method AutoConnect using the GetNeighboursHandler delegate as a parameter.

    public delegate List<GridTile> GetNeighboursHandler(GridTile c);

    public List<GridTile> GetTopNeighbour(GridTile c)
    {
        //do stuff and return list
        return null;
    }
     public GridTile AutoConnect(GridTile c, GetNeighboursHandler del)
    {
        List<GridTile> tempList = del(c);

        // do stuff with the tempList
    }

    public void Test(GridTile c)
    {
        AutoConnect(c, GetTopNeighbour(c));
    }

In the Test method I get the error: ... cannot convert ...Generic.List...to GetNeighboursHandler. Have I completely misunderstood how delegates work?

Upvotes: 1

Views: 53

Answers (3)

TheLastStark
TheLastStark

Reputation: 800

You need to pass a delegate (which is an object that knows how to call the method, ie: it holds the reference of a method) What you have done is passing the function result that you get after it's execution GetTopNeighbour(c) returns a List<GridTile>, and you are passing this return value in your code here

AutoConnect(c, GetTopNeighbour(c));

Instead you should pass the reference to that method GetTopNeighbour

AutoConnect(c, GetTopNeighbour);

Refer these This is a tutorial and here's another one

Upvotes: 2

Jonathon Chase
Jonathon Chase

Reputation: 9704

You're passing the result of GetTopNeighbour(c), which is a List<GridTile>, as a parameter to AutoConnect.

Instead, you want to pass the MethodGroup to be converted to a delegate, like so:

AutoConnect(c, GetTopNeighbour);

Upvotes: 1

adjan
adjan

Reputation: 13652

You have to pass the method (or rather, method group) itself, instead of calling it:

AutoConnect(c, GetTopNeighbour);

Upvotes: 1

Related Questions