Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining C# events without an external delegate definition

just out of curiosity: is it possible to define events in C# without defining a delegate type beforhand?

something like public event (delegate void(int)) EventName

like image 735
knittl Avatar asked Mar 19 '11 15:03

knittl


2 Answers

There's built in generic delegate types, Action<> and Func<>, where Action returns void. Each generic type argument is type type of the argument to be passed to the delegate. e.g.

public event Action<int> EventName;

Also, there's a generic EventHandler<T> to follow the convention of passing the Object sender, and having an EventArgs type.

like image 195
Mark H Avatar answered Oct 12 '22 08:10

Mark H


No, it is not possible; ECMA-334, § 17.7 states:

The type of an event declaration shall be a delegate-type (§11.2)

and § 11.2 defines:

delegate-type:
    type-name

However, since C# 3, you can use various predefined generic types such as Action<int> so that you almost don’t have to define your own delegate types.

like image 37
Mormegil Avatar answered Oct 12 '22 07:10

Mormegil