Reputation: 83
I am trying to understand if all of the options below are viable. I completely understand the delegate and event usage, but Action seems to provide syntactic sugar by making it even easier (or am I missing something)? I have tested all of these and they work, but that doesn't mean they are all good patterns.
public delegate WorkCompleteDel(sting value);
public class MyClass{
//Are these all viable, safe options?
//ties the above delegate, pretty standard pattern
public event WorkCompleteDel WorkCompletedDelEvent;
//OR
//this seems to be the easiest but only supports
//on listner/subscriber. IF thats all you need, seems
//reasonble?
public Action<string> WorkCompleteHandler1 {get; set;}
//OR
//this is similar to the one below it but
//uses an action. Not sure if using he event keyword
//now gives me the ability to have multple subscibers
//(but I think it does due to multicast delegate class)
public event Action<string> WorkCompleteHandler1;
//OR
//another standard patthen
public event EventHandler<MyEventHandlerArgs> WorkCompleteHandler2
}
public class MyEventHandlerArgs: EventArgs
{
public string MyString {get; set}
}
Upvotes: 4
Views: 6946
Reputation: 6950
Action<T>
is just an easy generic way to use delegates. It's equivalent to delegate MyDelegate(T arg)
It was added to save you some typing and it really saves the reader a LOT of hassle when trying to figure out what your delegate uses as parameters.
The event
keyword has special meaning. It prevents this delegate from being triggered outside of the class. See this excellent answer for a discussion of why event
is important and when you would use it (or not).
Upvotes: 8