9.9. Using Different Parameter Modifiers in Lambda Expressions

Problem

You know you can pass parameters to lambda expressions, but you need to figure out what parameter modifiers are valid with them.

Solution

Lambda expressions can use out and ref parameter modifiers but not the params modifier in their parameter list. However, this does not prevent the creation of delegates 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 a lambda expression, as you'll see in a bit. To use the DoOutWork delegate, create a lambda expression inline using the out keyword and assign it to the DoOutWork delegate instance. Inside the lambda expression 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. Note that in the parameter list, the type of s (string) must be provided, as it is not inferred for a variable marked with the out keyword. It is not inferred for out or ref variables to preserve the representation at the call site and the parameter declaration site to help the developer clearly reason about the possible assignment to these variables:

 // Declare ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.