Reputation: 7136
I am looking at the old VB.net code
Public Event TagDetected(ByVal t As Tag)
...
RaiseEvent TagDetected(t)
that I am trying to convert to C#. My attempt:
public event EventHandler<Tag> TagDetected;
...
TagDetected(this, t.Clone());
doesn't work and gives me an error:
Error 1 The type 'XYZ.VKM.Common.Tag' cannot be used as type parameter 'TEventArgs' in the generic type or method 'System.EventHandler'. There is no implicit reference conversion from 'XYZ.VKM.Common.Tag' to 'System.EventArgs'.
Upvotes: 0
Views: 151
Reputation: 6542
There are 2 forms of an event declaration in VB - one uses an explicit delegate type and the other uses an implicit delegate type - you used the implicit delegate approach. C# only has the explicit delegate type approach. The equivalent C# code is:
public delegate void TagDetectedEventHandler(Tag t);
public event TagDetectedEventHandler TagDetected;
Upvotes: 2
Reputation: 9571
The EventHandler{TEventArgs} delegate is for a function that takes a generic type which derived from the EventArgs class. In your example, the Tag
class doesn't derive from EventArgs
which is why you're getting an error.
The event
keyword doesn't have to be used with either the EventHandler
or EventHandler{TEventArgs}
delegates, but actually any delegate. In this particular case you can better translate the code as follows:
public event Action<Tag> TagDetected;
...
TagDetected(t.Clone());
Upvotes: 3
Reputation: 3256
I think you meant to write:
public event EventHandler<TagEventArgs> TagDetected;
where TagEventArgs is your own child class of EventArgs, exposing a DetectedTag property. This makes sure that the event handler pattern is tightly observed (i.e. you can always refer to the EventArgs as EventArgs in any handler, not having to know that they're just an int, or in your case, just a tag).
Upvotes: 2