Click here to Skip to main content
13,198,075 members (81,500 online)
Click here to Skip to main content
Add your own
alternative version


16 bookmarked
Posted 22 Apr 2008

Nested Functions in C#

, 22 Apr 2008
Rate this:
Please Sign up or sign in to vote.
This article tells you about writing nested functions in C#


We all have heard of nested classes, nested namespaces. Have we ever heard of nested functions??? Can we write a nested function in C#???

The answer is Yes, we can write a nested function in C# using delegates. This article deals with writing nested methods in C#. Knowledge of delegates is required. For creating nested methods, we write anonymous methods and associate delegates with them.

Using the Code

For writing a nested function in C#, we would make use of delegates and anonymous functions. A delegate is nothing but a "function pointer". And an anonymous function is a function/method without a name. Below, we are declaring a delegate which will point to an anonymous function.

// Declare a delegate which will point to different anonymous methods.
public delegate long FactorialDelegate(long n);        

After declaring the delegate, we will write the anonymous functions as given below:

// This method defines anonymous functions.           
public static void FunctionInFunction()
    // Nested function.
    FactorialDelegate FactorialMethod = delegate(long number)
        if (number < 1)
            throw new ArgumentOutOfRangeException(
            "n", "Argument must be greater than 0!");

        long result = 1;

        // Calculate factorial
        for (int iterator = 1; iterator <= number; iterator++)
        result *= iterator;

        return result;

    // Nested function with recursion.
    FactorialDelegate FactorialRecursive = delegate(long number)
        if (number < 1) throw new
            "n", "Argument must be greater than 0");
    // The current method will always be at the 0th frame on the stack.
    MethodBase method = new StackTrace().GetFrame(0).GetMethod();

    return number > 1 ? number * (long)method.Invoke(null,
        new object[] { number - 1 }) : number;

Console.WriteLine("Factorial for 5 = " + FactorialMethod(5));

Console.WriteLine("Factorial for 10 = " + FactorialRecursive(10));

In the above example, we have declared a delegate and in the method FunctionInFunction, we are associating that delegate with two anonymous methods we defined. The first one is a normal method and the second anonymous method is recursive in nature. In the recursive method, we have used reflection to get the recursive method name, i.e. invoking this method. The current method will always be on the frame 0 of the stack trace.

Some properties of anonymous methods are as follows:

  • It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block whose target is outside the block. It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block whose target is inside the block.
  • Unlike local variables, the lifetime of the outer variable (outer variable is a variable declared local to the outside wrapper function) extends until the delegates that reference the anonymous methods are eligible for garbage collection.
  • An anonymous method cannot access the ref or out parameters of an outer scope.
  • No unsafe code can be accessed within the anonymous-method-block.

More information on anonymous function can be found here.

Points of Interest

This is a wonder that we can do with delegates.


  • 23rd April, 2008: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sandeep Aparajit
Software Developer (Senior)
United States United States
Sandeep has 9+ yrs of IT experience. He is Microsoft Certified Technology Specialist and has been certified for Analyzing Requirements and Defining Microsoft .NET Solution Architectures.
He is an active member of:
1. MSDN Forums

My Blog
More Info

You may also be interested in...

Comments and Discussions

GeneralIt doesn't seem worth the trouble Pin
PIEBALDconsult23-Apr-08 17:32
memberPIEBALDconsult23-Apr-08 17:32 
QuestionWhy stay at the 0th frame of the stack? Pin
elektrowolf23-Apr-08 3:45
memberelektrowolf23-Apr-08 3:45 
AnswerRe: Why stay at the 0th frame of the stack? Pin
johannesnestler23-Apr-08 4:05
memberjohannesnestler23-Apr-08 4:05 
GeneralRe: Why stay at the 0th frame of the stack? Pin
elektrowolf23-Apr-08 6:46
memberelektrowolf23-Apr-08 6:46 
GeneralIt's not called a nested function Pin
leppie23-Apr-08 3:19
member leppie 23-Apr-08 3:19 
It is more commonly called a closure, but only if the anonymous function declaration actually captures the lexical environment. In your sample, none of your anonymous function declarations capture the environment, and they are simply syntactic sugar for delegates.

To explain the captured environment, look at the following:
delegate int Bar();
Bar Foo()
  int i = 0;
  return delegate
    return i;
Bar b = Foo();
int i = b(); 1 is returned
i = b(); 2 is returned
i = b(); 3 is returned
i = b(); 4 is returned

The compilation of the above is much more complicated.

xacc.ide - now with TabsToSpaces support
IronScheme - 1.0 alpha 3 out now

GeneralBrilliant! Pin
Nick Butler23-Apr-08 2:35
memberNick Butler23-Apr-08 2:35 
GeneralIt is not true as it seems Pin
J@@NS22-Apr-08 22:22
memberJ@@NS22-Apr-08 22:22 
GeneralRe: It is not true as it seems Pin
leppie23-Apr-08 3:11
member leppie 23-Apr-08 3:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171020.1 | Last Updated 23 Apr 2008
Article Copyright 2008 by Sandeep Aparajit
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid