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?

user2341923
  • 4,537
  • 6
  • 30
  • 44
  • It seems from this [Roslyn issue](https://github.com/dotnet/roslyn/issues/2930) that *Attributes (perhaps not allowed on the function)* have not been implemented. – DavidG Apr 19 '17 at 14:44
  • 2
    No, its not possible. If it were, your code would compile. – InBetween Apr 19 '17 at 15:05
  • @InBetween That's not really an answer is it, they could (for some crazy reason) have changed the syntax for attributes in local functions. – DavidG Apr 19 '17 at 15:11
  • 1
    @DavidG 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. – InBetween Apr 19 '17 at 15:13
  • @InBetween 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! – DavidG Apr 19 '17 at 15:56

2 Answers2

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.

vulcan raven
  • 32,612
  • 11
  • 57
  • 93
Jon S
  • 158
  • 9
  • @PetSerAl, there's an example at the bottom using [CallerMemberName]. You can see a similar example here: http://www.nimaara.com/2017/04/01/local-functions-a-new-c/ – Jon S Apr 19 '17 at 19:13
1

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

Roger Sanders
  • 2,232
  • 1
  • 22
  • 29