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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With