Google
 

Tuesday, June 05, 2007

What is and how to use System.Action ?

REF: http://msdn2.microsoft.com/en-us/library/018hxwa8.aspx
Represents the method that performs an action on the specified object.

Remarks

This delegate is used by the Array.ForEach method and the List.ForEach method to perform an action on each element of the array or list.

The following example demonstrates the use of the Action delegate to print the contents of a List object. In this example, the Print method is used to display the contents of the list to the console.

NoteNote:

In addition to displaying the contents using the Print method, the C# example also demonstrates the use of Anonymous Methods (C# Programming Guide) to display the contents to the console.



using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
List
<String> names = new List<String>();
names.Add(
"Bruce");
names.Add(
"Alfred");
names.Add(
"Tim");
names.Add(
"Richard");

// Display the contents of the List out using the "Print" delegate.
Console.WriteLine("Using Action");
names.ForEach(Print);

// The following demonstrates the Anonymous Delegate feature of C#
// to display the contents of the List to the console.
Console.WriteLine("Using Anonymous Delegate feature");
names.ForEach(
delegate(String name){
Console.WriteLine(name);
}
);

Console.Read();
}

private static void Print(string s)
{
Console.WriteLine(s);
}
}

No comments: