Can MethodImplAttribute be applied to local functions (and possibly lambdas)?


#1

I have just noticed that the MethodImplAttribute cannot be applied to a local function … And I’m just wondering why that is true.

I don’t have rationale for use cases in general, and I just wrote a method where I’d actually desire to add AggressiveInlining to a local function.

Just a simple example:

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private void handleMessage(MessageBase message)
    {
        // Can't apply:
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        bool update(IMappedQueue mappedQueue)
        {
        }
    }

In a dream world, I would like to envision that the local function could be inlined. I haven’t actually inspected compiled code to see what ultimately happens — it might in fact get inlined — but it would be nice to be able to apply the attribute.

And I also don’t know if it could be applied to lambdas, but seems potentially plausible.

Thanks for listening!


#2

You can’t apply attributes to local functions at all, the syntax just doesn’t allow it. There is a discussion about allowing this on the csharplang repo, and AggressiveInlining is already listed as one of the use-cases where attributes on local functions would be useful.


#3

Thanks @svick :clown_face:.


.NET Foundation Website | Blog | Projects | Code of Conduct