Is it possible to create a function inside another function in C#? If so, how can this be done?
We can declare a function inside a function, but it's not a nested function. Because nested functions definitions can not access local variables of the surrounding blocks, they can access only global variables of the containing module.
To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.
If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.
A nested function is a function defined inside the definition of another function. It can be defined wherever a variable declaration is permitted, which allows nested functions within nested functions. Within the containing function, the nested function can be declared prior to being defined by using the auto keyword.
It is most certainly possible.
You can create delegates, which are functions, inside other methods. This works in C# 2.0:
public void OuterMethod() {
someControl.SomeEvent += delegate(int p1, string p2) {
// this code is inside an anonymous delegate
}
}
And this works in newer versions with lambdas:
public void OuterMethod() {
Func<int, string, string> myFunc = (int p1, string p2) => p2.Substring(p1)
}
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