Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an out parameter not allowed within an anonymous method?

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

like image 909
Chris Ballance Avatar asked Oct 28 '09 15:10

Chris Ballance


People also ask

Can you use ref and out parameters in lambda expression if declared outside?

In lambda expressions, you can't use the ref or out parameters.

What is anonymous methods?

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.

How to declare anonymous method in C#?

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.

Can out parameter be optional C#?

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.


2 Answers

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?

like image 105
JaredPar Avatar answered Oct 02 '22 16:10

JaredPar


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.)

like image 26
Noldorin Avatar answered Oct 02 '22 18:10

Noldorin