The events are quite mundane. Most often, you will use them in response to a user interface or when developing components that should notify users of government changes. Yon.
The delegates, however, are full of fear and victory. Probably the most common use is in Linq. Linq uses lambdas all over the place that are abbreviated delegates.
var numbers = new int[]{1,2,3,4,5}; var evenStevens = numbers.Where(x => x % 2 == 0);
Another common use is multithreading:
ThreadPool.QueueUserWorkItem(o => DoWork(o));
Where I used them, which I like most, in the HtmlHelper extension methods that mix html rendering with codebehind:
/// <summary> /// Helps render a simple list of items with alternating row styles /// </summary> /// <typeparam name="T">The type of each data item</typeparam> /// <param name="html">The HtmlHelper.</param> /// <param name="rows">The list of items</param> /// <param name="rowTemplate">The row template.</param> /// <param name="evenCssClass">The even row CSS class.</param> /// <param name="oddCssClass">The odd row CSS class.</param> public static void SimpleList<T>( this HtmlHelper html, IEnumerable<T> rows, Action<T, string> rowTemplate, string evenCssClass, string oddCssClass) { var even = false; foreach (var row in rows) { rowTemplate(row, even ? evenCssClass : oddCssClass); even = !even; } }
An example of its use in an aspx file:
<div id="nodes" class="scrollingBlock">> <% Html.SimpleList( Model.Nodes, (d, css) => {%> <div class='<%=css%>'><%=d.Name %></div> <%}, "evenRow", "oddRow");%> </div>
source share