Reputation: 13434
Is it possible to create a function inside another function in C#? If so, how can this be done?
Upvotes: 13
Views: 16974
Reputation: 4899
As of C# 7.0 you can do that:
public static void SlimShady()
{
void Hi([CallerMemberName] string name = null)
{
Console.WriteLine($"Hi! My name is {name}");
}
Hi();
}
This is called local funtions, that is just what you were looking for.
I took the example from here, but further informatin can be found here and here.
Upvotes: 12
Reputation: 3393
You can do this in c# 7(need VS 2017)
static void Main(string[] args)
{
int fib0 = 1; //!
int Fib(int n) => (n < 2) ? fib0 : Fib(n - 1) + Fib(n - 2);
Console.WriteLine(Fib(7));
Console.ReadKey();
}
Upvotes: 12
Reputation: 9
It's so not code smell that X++ has it done in the simplest way possible...
public void PublicMethod() {
void LocalMethod() {
//do stuff
}
LocalMethod();
}
see http://msdn.microsoft.com/en-us/library/aa637343.aspx
Upvotes: -1
Reputation: 703
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.
Upvotes: -2
Reputation: 25704
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)
}
Upvotes: 17