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:

Post a Comment

Comments are welcome but I do moderate them. This is simply to keep things wholesome for general family viewing. By default, comments will be accepted. The few things that will cause a comment to be rejected are:

1. It is too long even though it may be well-written and make interesting points. It's supposed to be a comment, not an essay. If you have that much to say, write a blog article and backlink to me.

2. It is nasty, impolite or uses language that is unacceptable.

3. It includes a a link that has a typo or is broken in some other way.

4. It should have been sent as an e-mail since it is clearly addressed to me and does not appear to have been intended for other readers.

5. It is blatantly self-promotional. This does not mean it can't be self-promotional at all, but it should add some value over an above the marketing.