tags:

views:

81

answers:

2

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

+2  A: 

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)
}
Eilon
Really interesting, I learnt something :)Could you give use cases for those "delegates" that are created inside other functions please ?
Andy M
These types of delegates and lambdas are often used when a piece of code is so small it's not worth giving it a name. This other SO question goes a bit more into when it could/should be used: http://stackoverflow.com/questions/2047053/when-should-i-use-lambda-expressions-which-comes-with-c-3-0
Eilon
I use it fairly often to declare a job for a BackgroundWorker: http://stackoverflow.com/questions/1952201/display-progress-bar-while-doing-some-work-in-c/1969933#1969933
Oliver
thank you for ur answer could give more explanation and any possible ways
ratty
+1  A: 

Eilon's answer is technically correct in that you can use delegates to effectively create a method within a method. The question I would ask is why you need to create the function in-line at all?

It's a bit of a code smell to me. Yes, the internal method is reusable to the rest of your method, but it suggests that there is an element of the code where the design hasn't really been thought through. Chances are, if you need to use a delegate in this way, you would likely to be doing something fairly small and repetitive that would be better served as a function in the class, or even in a utility class. If you are using .Net 3.5 then defining extensions may also be a useful alternative depending on the usefulness of the code being delegated.

It would be easier to answer this question better if you could help us to understand why you feel the need to write your code in this way.

S.Robins
Not fully convinced about the code smell bit. For me it's no different that declaring a local variable. You create a local variable for a local purpose, nobody uses it and it's not worth promoting it to a field of the class. The same goes with lambdas - just declare a local function.
Mathias
To clarify, the "smell" is that even with lambdas, you could find the same small snippets of code being repeated all over a large application. It might not seem likely until you take into account the inherent problem with unmonitored Cut-Paste coding. And yes, repetitively using the same pattern of local variables could be seen in the same way. I'm not saying not to use lambdas or in-line delegates mind you, just noting that they shouldn't be used as a substitute for taking the time to design your algorithms properly.
S.Robins