Friday, July 8, 2011

Local procedures from Delphi in C#

Pascal has this nifty feature where you can declare procedures inside of procedures. Something like:
procedure procA

    procedure procB
    begin
        // procedure B code here
    end;

begin
    // procedure A code here calling procB
end;

It's not the type of thing I used a lot, but there were times where it came in handy. It was a nice thing to have in the tool belt even if it wasn't pulled out too often. A couple times I have wanted to do this in C# and have resorted to other means.

Today while reading an article by John Cook about C++, I realized this is trivially easy to do in C#: simply use named lambdas. It's one of those things that's so obviously simple and easy, I don't know why it didn't occur to me before.

So, the above Pascal code could be written in C# like so:
public void procA()
{
    Action procB = () => 
        {
            // procedure B code here
        }

    // procedure A code here calling procB()
}

No comments: