This is not a dupe of Calling a method with ref or out parameters from an anonymous method
I am wondering why out parameters are not allowed within anonymous methods. Not allowing ref parameters makes a bit more sense to me, but the out parameters, not as much.
what are your thoughts on this
In lambda expressions, you can't use the ref or out parameters.
An anonymous method is a method which doesn't contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods.
Anonymous methods are declared with the creation of the delegate instance, with a delegate keyword. For example, delegate void NumberChanger(int n); ... NumberChanger nc = delegate(int x) { Console.
No. To make it "optional", in the sense that you don't need to assign a value in the method, you can use ref . A ref parameter is a very different use case.
In some ways this is a dupe. Out
parameters are ref
parameters. There is simply an extra attribute on the value that is used by the C# language. The reason for disallowing them is the exact same as ref
parameters.
The problem here originates with the effect of using a value declared outside the anonymous method within the anonymous method. Doing so will capture the value within the lambda and out of necessity arbitrarily extend its lifetime beyond that of the current function. This is not compatible with out
parameters which have a fixed lifetime.
Imagine for instance that the out
parameter referred to a local variable on the stack. The lambda can execute at any arbitrary point in the future and hence could execute when that stack frame was no longer valid. What would the out
parameter mean then?
This is basically to do with the fact that parameters of an anonymous delegate/lambda expressions are captured variables, and capturing ref
/out
variables doesn't make any sense in C#/the CLR, since it would require ref
/out
fields internally. Also, note that I pair both these keywords because they are effectively the same.
If you want a complete explanation, Eric Lippert discussed this design point in detail on his blog. (See the paragraphs near the bottom in particular.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With