user4466599
user4466599

Reputation:

Generic Delegate

I want to have a delegate for a method which takes one parameter and returns a result, both of the same type. I also want the type to be determined by a generic type argument but the following syntax fails me.

delegate T SomeDelegate(T param)<T>;

How could I achieve this?

Upvotes: 1

Views: 97

Answers (2)

BendEg
BendEg

Reputation: 21128

You have to put<T> between the Delegate-Name and the open bracket: delegate T SomeDelegate<T>(T param);. After the close-bracket you can only say, which type T must be, to be sure the correct types are passed. For example:

delegate T SomeDelegate<T>(T param) where T : IDisposable;

Often this is necessary, to be sure that T is inherited by Disposable. So you later can cast T as IDposposable and call some method of the interface.

Notice, only interfaces can be user for filtering.

Upvotes: 2

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29233

The type parameter must be declared between the method/delegate name and the regular parameter list:

delegate T SomeDelegate<T>(T param);

Upvotes: 5

Related Questions