Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an Attribute to Lambda function in C#? [duplicate]

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?

like image 412
ANGeL-Devon Avatar asked Sep 26 '22 05:09

ANGeL-Devon


1 Answers

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

like image 69
Anders Marzi Tornblad Avatar answered Sep 29 '22 07:09

Anders Marzi Tornblad