Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
548
|
Chapter 9: Delegates, Events, and Anonymous Methods
// Declare instance.
DoWork dw = delegate(string s)
{
Console.WriteLine(s);
foreach (string item in items)
{
Console.WriteLine(item);
}
return s.GetHashCode( );
};
// Invoke delegate.
int i = dw("DoWorkMethodImpl1");
}
Since the params modifier is there for the benefit of the calling site (so the compiler
knows to make this a method call that supports variable-length argument lists) and
since anonymous methods are never called directly (always called via a delegate),
then it makes no sense for an anonymous method to be decorated with something
there for the benefit of the calling site—there is no calling site. This is why it doesn’t
matter that you can’t use the
params keyword on an anonymous method. For anony-
mous methods, the calling site is always calling through the delegate, so what mat-
ters is whether that delegate has the
params keyword or not.
See Also
See Recipe 9.12; see the “CS1670,” “CS1628,” “out,” “ref,” “params,” and “System.
ParamArrayAttribute” topics in the MSDN documentation.
9.15 Using Closures in C#
Problem
You want to associate a small amount of state with some behavior without going to
the trouble of building a new class.
Solution
Use anonymous methods to implement closures. Closures can be defined as func- ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
C# Cookbook

C# Cookbook

Joe Mayo
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata