Search code examples
c#lambdacustom-attributes

How to add an Attribute to Lambda function in C#?


I have a custom attribute in C#: MyAttr. And I have a method that expects a delegate as parameter.

I now pass in a lambda expression to that method:

SomeMethod((object o) => { DoSomething(); });

That DoSomething() method uses relfection to get information about the calling method (in this case lambda expression). But it can't find the needed information, becauce the lambda expression does not have an attribute :-(

What I want to do is one of the following:

// This does not work:
SomeMethod([MyAttr](object o) => { DoSomething(); });
// Thos does not work, too:
SomeMethod((object o) => [MyAttr] { DoSomething(); });

Is it possible at all to put an attribute to a lambda expression?


Solution

  • That is not possible yet, unfortunately. You will have to this the "old way", by creating a delegate method with the attribute. As xanatos points out, this might be in the next version of C#, however.

    [MyAttr]
    private void MyCallback(object o)
    {
    }
    

    Actually, this question already has an answer here: Custom attribute on parameter of an anonymous lambda

    EDIT (seven years later)

    From C# 10, this is now possible.

    // This does work from C# 10:
    var lambda = [MyAttr] (object o) => { DoSomething(); };
    SomeMethod(lambda);