Skip to content

Add support for static anonymous functions#988

Closed
RexJaeschke wants to merge 6 commits intodotnet:draft-v9from
RexJaeschke:Add-support-for-static-anonymous-functions
Closed

Add support for static anonymous functions#988
RexJaeschke wants to merge 6 commits intodotnet:draft-v9from
RexJaeschke:Add-support-for-static-anonymous-functions

Conversation

@RexJaeschke
Copy link
Contributor

No description provided.

@RexJaeschke RexJaeschke added the type: feature This issue describes a new feature label Nov 12, 2023
@RexJaeschke RexJaeschke added this to the C# 9.0 milestone Nov 12, 2023
@RexJaeschke RexJaeschke marked this pull request as draft November 12, 2023 18:58

A non-`static` local function or non-`static` anonymous function can capture state from an enclosing `static` anonymous function, but cannot capture state outside the enclosing static anonymous function.

Removing the `static` modifier from an anonymous function in a valid program does not change the meaning of the program.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should static ensure that all delegate instances converted from the same anonymous function shall compare equal? (That would not require any caching of delegate instances.)

using System;
using System.Diagnostics;

class C {
    Action G() {
        return static () => {};
    }
    void M() {
        Debug.Assert(G() == G());
    }
}

I think static should not guarantee this equality. IIRC Roslyn generates an instance method even for a static anonymous function because it is more efficient for the calling convention. Then the delegate will refer to some instance, and will compare unequal if it refers to a different instance. Requiring such an implementation to ensure that the same instance is used every time might cost additional interlocked operations for thread safety.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a note about this in the specification of delegate equality would be useful though.

@BillWagner
Copy link
Member

Closing in favor of #1461

@BillWagner BillWagner closed this Nov 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feature This issue describes a new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants