delegate

T

Tony Johansson

Hello!

Delegate is normally set up in this way using the += construction.
Here an example on event Elapsed in class Timer.
pollTimer.Elapsed += new ElapsedEventHandler(CheckForMessage);
where method CheckForMessage has signature
private void CheckForMessage(object sender, ElapsedEvebtArgs e)
{}

Here I have Comparison<T>. This is a delegate type that can be used for
sorting when the delegate
method has this signature
int method (T objectA, objectB) {}
This construction
Comparison<Vector> sorterDelegat = new Comparison<Vector>
(someSuitableMethodForSort);
works fine setting up a delete method that can be used for example when
sorting

But why is is it not possible to use += in this way. If I try with += I get
compiler error
because the syntax is not understandable by the compiler.
Comparison<Vector> sorterDelegat += new Comparison<Vector>
(VectorDelegates.Compare);
This work always when setting up a delegete method that can be used when the
event is trigged.

//Tony
 
J

Jon Skeet [C# MVP]

Delegate is normally set up in this way using the += construction.

Define "normally". You usually subscribe to an event that way, but
using delegates in LINQ to Objects almost never uses += for example.
Here an example on event Elapsed in class Timer.
pollTimer.Elapsed += new ElapsedEventHandler(CheckForMessage);
where method CheckForMessage has signature
private void CheckForMessage(object sender, ElapsedEvebtArgs e)
{}

Okay - an event based example.
Here I have Comparison<T>. This is a delegate type that can be used for
sorting when the delegate
method has this signature
int method (T objectA, objectB) {}
This construction
Comparison<Vector> sorterDelegat = new Comparison<Vector>
(someSuitableMethodForSort);
works fine setting up a delete method that can be used for example when
sorting

But why is is it not possible to use += in this way. If I try with += I get
compiler error
because the syntax is not understandable by the compiler.
Comparison<Vector> sorterDelegat += new Comparison<Vector>
(VectorDelegates.Compare);
This work always when setting up a delegete method that can be used when the
event is trigged.

That's because it's *adding* a handler for an event. Here you're just
trying to declare and initialize a new variable. It's the equivalent
of writing something like:

int i += 10;

Jon
 
I

Ignacio Machin ( .NET/ C# MVP )

Hello!

Delegate is normally set up in this way using the += construction.


Not really, you use the += with events. not with delegates.
That an event has a type that needs to be a delegate is another
subject.

delegates can and are used without an event.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top