Nested Methods / Sub Methods

Topics: C# Language Design
Apr 12, 2014 at 10:40 AM
Very often we need some small functions that will be called only from some main function one or few times.
public      void        SomeBigLogic    ( )     
{
    //...
    InternalPartOfSomeBigLogic_1( );
    //...
    InternalPartOfSomeBigLogic_2( );
    //...
    InternalPartOfSomeBigLogic_1( );
    //...
}
private     void        InternalPartOfSomeBigLogic_1    ( )     
{
    //...
}
private     void        InternalPartOfSomeBigLogic_2    ( )     
{
    //...
}
These "InternalPart" functions never will be and never should be used outside "SomeBigLogic" and can be nested inside it. Nested Methods is always private Methods that can not be called froum outside the Method that it nested in.
public      void        SomeBigLogic    ( )     
{
    //...
    InternalPartOfSomeBigLogic_1( );
    //...
    InternalPartOfSomeBigLogic_2( );
    //...
    InternalPartOfSomeBigLogic_1( );
    //...


    void        InternalPartOfSomeBigLogic_1    ( )     
    {
        //...
    }
    void        InternalPartOfSomeBigLogic_2    ( )     
    {
        //...
    }
}
No IL changes. Nested methods sould be compiled like regular private member or static method with [NestedIn("NameOfParentMethod")] attribute.

Comments. :)
Apr 12, 2014 at 11:26 AM
I'm not sure what problem does this solve exactly but you can do it already by using lambda expressions:
class Something {
    private int y = 21;

    private void Do() {
        Func<int, int> Frob = x => {
            return x * y;
        };

        Console.WriteLine(Frob(21));
    }
}

Apr 12, 2014 at 11:35 AM
Lambda more hard it is not just call instruction so I cannot use this in any bottleneck code ( i.e. collision logic ) because of hudge overhead.

And also that code do not clear. It hard to read and write.
Apr 13, 2014 at 12:36 AM
What would be the difference between this and just defining additional methods within the same class? Unless you're also looking for something like variable lifting, where the nested function can implicitly reference variables from the parent method, I don't see any difference.
Apr 13, 2014 at 11:52 AM
@JesInc28: Have you measured the overhead and determined it to be unacceptable in your scenario?