
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
|
547
So this illustrates that you can bind an anonymous method to a delegate declared
using
params, and once you’ve done that, you can call it passing in any number of
parameters you like just as you’d expect.
Discussion
Anonymous methods cannot access the ref or out parameters of an outer scope. This
means any
out or ref variables that were defined as part of the containing method
are off-limits for use inside the body of the anonymous method.
// Declare delegate.
delegate int DoWork(string work);
public void TestOut(out string outStr)
{
// Declare instance.
DoWork dw = delegate(string s)
{
Console.WriteLine(s);
// Causes error CS1628:
// "Cannot use ref or out parameter 'outStr' inside an
// anonymous method block"
//outStr = s;
return s.GetHashCode( );
};
// Invoke delegate.
int i = dw("DoWorkMethodImpl1");
}
public void TestRef(ref string refStr)
{
// Declare instance.
DoWork dw = delegate(string s)
{
Console.WriteLine(s);
// Causes error CS1628:
// "Cannot use ref or out parameter 'refStr' inside an
// anonymous method block"
// refStr = s;
return s.GetHashCode( );
};
// Invoke delegate
int i = dw("DoWorkMethodImpl1");
}
Interestingly enough, anonymous methods can access outer variables with the params
modifier.
// Declare delegate. ...