Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create function inside another function in c#,is it possible?

Tags:

methods

c#

Is it possible to create a function inside another function in C#? If so, how can this be done?

like image 572
ratty Avatar asked Jan 12 '10 06:01

ratty


People also ask

Can a function be inside another function in C?

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.

How do you put a function inside another function?

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.

Can we define a function inside another 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.

What is nested function in C with example?

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.


1 Answers

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)
}
like image 182
Eilon Avatar answered Oct 28 '22 18:10

Eilon