For example,
public int DoSomething(in SomeType something){
int local(){
return something.anInt;
}
return local();
}
Why does the compiler issue an error that the something variable cannot be used in the local function?
For example,
public int DoSomething(in SomeType something){
int local(){
return something.anInt;
}
return local();
}
Why does the compiler issue an error that the something variable cannot be used in the local function?
Copyright © 2021 Jogjafile Inc.
The documentation on local functions states the following
Variable capture
And looking at lambdas:
Capture of outer variables and variable scope in lambda expressions
The reason is simple: it's not possible to lift these parameters into a class, due to
refescaping problems. And that is what would be necessary to do in order to capture it.Example
Suppose this function is called like this:
The
Mysteryfunction creates aghostand passes it as aninparameter toDoSomething, which means that it is passed as a read-only reference to theghostvariable.The
DoSomethingfunction captures this reference into the local functionlocal, and then returns that function as aFunc<int>delegate.When the
Mysteryfunction returns, theghostvariable no longer exists. TheScaryfunction then uses the delegate to call thelocalfunction, andlocalwill try to read theanIntproperty from a nonexistent variable. Oops.The "You may not capture reference parameters (
in,out,ref) in delegates" rule prevents this problem.You can work around this problem by making a copy of the
inparameter and capturing the copy:Note that the returned delegate operates on the
copy, not on the originalghost. It means that the delegate will always have a validcopyto getanIntfrom. However, it means that any future changes toghostwill have no effect on thecopy.