
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Using Different Parameter Modifiers in Anonymous Methods
|
545
9.14 Using Different Parameter Modifiers
in Anonymous Methods
Problem
You know you can pass parameters to anonymous methods but you need to figure
out what parameter modifiers are valid with anonymous methods.
Solution
Anonymous methods can use out and ref parameter modifiers but not the params
modifier in their parameter list. However, this does not prevent the creation of dele-
gates with any of these modifiers as shown here:
// Declare out delegate.
delegate int DoOutWork(out string work);
// Declare ref delegate.
delegate int DoRefWork(ref string work);
// Declare params delegate.
delegate int DoParamsWork(params string[] workItems);
Even though the DoParamsWork delegate is defined with the params keyword on the
parameter, it can still be used as a type for an anonymous method, as you’ll see in a
bit. To use the
DoOutWork delegate, create an anonymous method inline using the out
keyword and assign it to the DoOutWork delegate instance. Inside the anonymous
method body, the
out variable s is assigned a value first (as it doesn’t have one by
definition as an
out parameter), writes it to the console, and returns the string hash
code.
// Declare instance and assign method.
DoOutWork dow = delegate(out string s)
{
s = "WorkFinished";
Console.WriteLine(s); ...