Modern C# supported definition of nested functions. For example:
public bool Test(params int[] args) {
bool isNumberValid(int i) {
return i > 0;
}
foreach(var n in args) {
if(!isNumberValid(n)) {
return false;
}
}
return true;
}
I wrote the above example only as a test case scenario and it doesn't matter if it can be refactored. Now the question is, how many times is the isNumberValid
function created? Is it created only once in such a way that it is moved outside the parent function block by the compiler? or is it created over over at runtime anytime the parent function is invoked (scoped under the parent stack)?
If you use a decompiler to inspect the output, you'll see something like this:
This shows that it has been compiled to a separate method, and is compiled only once.
Also note that for such a small local function in this example, the chances are that (for release mode builds) the JIT compiler will inline the function so that there isn't even a function call made for it.