C# 7 Local Functions: are attributes / aspects allowed?
Asked Answered
L

2

7

C# 7 introduced local functions (which is great!). Suppose I have the following code:

    using System;
    using PostSharp.Aspects;

    namespace AspectCS7
    {
        class Program
        {
            private static void Main()
            {
                [MyAspect]            
                void LocalFunction()
                {
                    Console.WriteLine("Hello Aspect!");
                }

                LocalFunction();
            }
        }

        [Serializable]
        public class MyAspect : OnMethodBoundaryAspect
        {
            public override void OnEntry(MethodExecutionArgs args)
            {
                Console.WriteLine("Entering Aspect");
            }
        }
    }

This code shows compile-time errors. Is it possible to apply attributes to local functions?

Larimore answered 19/4, 2017 at 14:36 Comment(5)
It seems from this Roslyn issue that Attributes (perhaps not allowed on the function) have not been implemented.Crystallography
No, its not possible. If it were, your code would compile.Hallway
@Hallway That's not really an answer is it, they could (for some crazy reason) have changed the syntax for attributes in local functions.Crystallography
@Crystallography And not document it anywhere? I find that hard to believe. If its not explicitly mentioned in whats new in C#7 documentation issued by Microsoft and the normal syntax doesn't work, I tend to believe the obvious: attributes are not allowed on local functions. It is an interesting feature though, DebuggerStepThrough can be sorely missed in some helper functions.Hallway
@Hallway I also find it hard to believe, but not impossible. There is no official C#7 spec, in fact, there is no official C#6 spec yet!Crystallography
C
2

Attributes were allowed on local functions at one point. There are some examples on the web of local functions using attributes, however they're not allowed anymore.

Update: Here is an ongoing discussion on this topic: https://github.com/dotnet/csharplang/issues/794.

Crumpled answered 19/4, 2017 at 17:36 Comment(1)
@PetSerAl, there's an example at the bottom using [CallerMemberName]. You can see a similar example here: nimaara.com/2017/04/01/local-functions-a-new-cCrumpled
T
1

This is an updated answer for 2023, to say this feature has now been implemented. It has been supported since mid 2020.

Tessie answered 12/4, 2023 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.