mowwwalker
mowwwalker

Reputation: 17334

Generic type to hold a delegate?

I have a method which takes a ThreadStart as a parameter and I usually call it like:

public void myMethod(ThreadStart ts) { ... }
myMethod(delegate () {...});

I would like to have this delegate assigned to a variable, though, before passing it into the function. When I use

Action myDel = delegate () {...};
myMethod(myDel);

.. I get an error about no matching method signature. What type can I make myDel so that it can be used interchangeably with the actual body of the delegate?

Upvotes: 0

Views: 81

Answers (2)

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13765

The reason for this is you cannot assign a delegate to another delegate(just because two classes have the same fields doesn't mean that you should be able to treat one as if it were another. The same logic applies to delegates) see this post by Jon Skeet "compatibility" doesn't necessarily meant that the signatures are identical)

So for example you can use this tricky mode to let your code work

        Action myDel = delegate () {};
         myMethod( new ThreadStart(myDel));

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101681

Why don't you define your myDel as a ThreadStart delegate like this ??

ThreadStart myDel = () => DoSomething();

ThreadStart and Action delegates signatures matching but they are different types. So you can simply define your delegate as a ThreadStart..

Upvotes: 2

Related Questions