Delegates vs. Function Pointers, part 4: C# 2.0+

This is part 4 in a series about state and function pointers; part 1 is here.

Last time, we saw that it is possible to pass local state with a delegate in C#.  However, it involves lots of repetitive single-use classes, leading to ugly code.

To alleviate this tedious task, C# 2 supports anonymous methods, which allow you to embed a function inside another function.  This makes my standard example much simpler:

//C# 2.0
int x = 2;
int[] numbers = { 1, 2, 3, 4 };

int[] hugeNumbers = Array.FindAll(
    numbers, 
    delegate(int n) { return n > x; }
);



//C# 3.0
int x = 2;
int[] numbers = { 1, 2, 3, 4 };

IEnumerable<int> hugeNumbers = numbers.Where(n => n > x);

Clearly, this is much simpler than the C# 1.0 version from last time.  However, anonymous methods and lambda expressions are compile-time features; the CLR itself is not aware of them.  How does this code work? How can an anonymous method use a local variable from its parent scope?

This is an example of a closure – a function bundled together with external variables that the function uses.  The C# compiler handles this the same way that I did manually last time in C# 1: it generates a class to hold the function and the variables that it uses, then creates a delegate from the member function in the class.  Thus, the local state is passed as the delegate’s this parameter.

To see how the C# compiler implements closures, I’ll use ILSpy to decompile the more-familiar C# 3 version: (I simplified the compiler-generated names for readability)

[CompilerGenerated]
private sealed class ClosureClass {
    public int x;
    public bool Lambda(int n) {
        return n > this.x;
    }
}
private static void Main() {
    ClosureClass closure = new ClosureClass();
    closure.x = 2;
    int[] numbers = { 1, 2, 3, 4 };
    IEnumerable<int> hugeNumbers = numbers.Where(closure.Lambda);
}

The ClosureClass (which was actually named <>c__DisplayClass1) is equivalent to the GreaterThan class from my previous example.  It holds the local variables used in the lambda expression.  Note that this class replaces the variables – in the original method, instead a local variable named x, the compiler uses the public x field from the ClosureClass.  This means that any changes to the variable affect the lambda expression as well.

The lambda expression is compiled into the Lambda method (which was originally named <Main>b__0).  It uses the same field to access the local variable, sharing state between the original outer function and its lambda expression.

Next time: Javascript

15 comments:

This information you provide us should be more visible to other readers. Gillian

The above article is nice and interesting, thank you willing to share! Greetings success of admin Percetakan Murah Rawamangun Jakarta Timur wish you deign to visit my website, thank you :)

This comment has been removed by the author.

Do you want to learn how to hack whatsapp? Here you can get more info about it

There is clearly a pack to think about this. I feel you offered unmistakable genuine articulations in highlights too. I obviously esteeming each and every piece of it. It is a phenomenal site and enchanting offer. I need to support your heart. Unprecedented business! Every one of you do an unprecedented blog, and make them stun substance. Keep doing superb. Visit my website Write my Essay

I see many good websites are available are giving cheap SEO service USA for the peoples who start up their business by taking service they get good responses from the peoples and Otherside we development is also gaining ground by marketing websites.

I have been looking for such information for a long time. Therefore, I am very grateful to you for sharing such a useful article. I also try to look for original sites that will be relevant for many students, you can view this source here .

Thank God we have got the upgraded tools these days where we do not have to work on the back for basic websites like I have (blogging one). Like the best British essay writers help help me with my academic work, similarly, these tools (WordPress and Wix) are making my professional life easier. So instead of relying on old ways I always try to incorporate smart ways.

امیر حسین افتخاری گره مو

دانلود آهنگ جدید امیر حسین افتخاری گره مو
دانلود آهنگ جدید

.

ترانه: امیر حسین افتخاری . تنظیم موزیک: امیر حسین افتخاری

I think these coding is not useful for our working because we have a very short time for marketing and we have to completed our work in time so that we convey Assignment writing service
for the students who live far from the UK

We provide these unique essays for our clients - https://softwaretested.com/technology/six-ways-software-influences-learning-positively/ - When you hire a writer for your essay from our service, you are assured that you would receive a 100% plagiarism-free composition.

This information you provide us should be more visible to other readers. looking for such information for a long time. Therefore, I am very grateful to you for sharing such a useful article. I also try to look for original sites. I simply couldn't leave your site just my reading this blog. I am really impressed with the content and way of writing. Keep sharing more.
child protective orders virginia
burden of proof for protective order in virginia .

Nice blog
Unlock your professional potential with our team of experts LinkedIn profile writers. Enhance your online presence with a tailored profile that highlights your skills and achievements.

สล็อต เล่นง่ายเข้าง่าย ปากทางเข้า สะสมเกมสล็อตพีจีออนไลน์ไว้อย่างยัดเยียดแล้วหลังจากนั้นก็เป็นเว็บที่มาแรงที่สุดของยุคนี้ PG SLOT เว็บตรงไม่ผ่านเอเย่นต์ แจ็กพอเพียงตแตกเยอะมาก

Post a Comment