Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# could we imagine writing our own events without writing delegates?

Tags:

java

c#

delegates

I learned the object-oriented in Java. Now in develop in C#. This means that I never really understood the functioning of delagates but I know how to use them.

Lately I discovered this page http://java.sun.com/docs/white/delegates.html.

If Java is able to create event without delagates is it possible to do the same in C#? Could we imagine writing our own events without writing a single delegate?

(Question already asked in french here)

like image 879
Bastien Vandamme Avatar asked Oct 30 '09 15:10

Bastien Vandamme


People also ask

What does -> mean in C?

Arrow operator to access the data member of a C Structure We have accessed the values of the data members using arrow operator(->).

What does %d do in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.


2 Answers

Yes, you could use a single-method interface instead of a delegate. You'd also need an implementation of the multi-cast nature of delegates, both in terms of add/remove and invoke. It would be tough to have a single class implementing multicast and also implementing Invoke in a typesafe way, however, due to the interfaces having different numbers and types of parameters. You could have a bunch of them of course: Multicast<T>, Multicast<T1, T2> etc. (The same class would handle asynchronous execution too, probably.)

The other pain in the neck is that you could only implement the interface once per class, even if you wanted several different handlers - so you'd have a lot of nested classes.

There's little that's particularly magical about delegates - they're just a very useful abstraction, and with the syntactic sugar of lambda expressions, anonymous methods and expression trees, they're even nicer.

like image 193
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet


No, you can't do events in C# without delegates. In C#, events are defined as delegates:

An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type.

However, you could mimic events using the Observer pattern.

Microsoft's answer to Sun's White Paper is worth reading.

like image 34
jason Avatar answered Oct 06 '22 00:10

jason