tags:

views:

64

answers:

2

Hi,

is there way how to get name ov event from Lambda expression like with property ( http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression ) ?

Thanks

+2  A: 

No. C# lambdas don't support events, so there is no way of representing this. You'll have to use reflection.

Marc Gravell
I don't want use things such as "GetEventInfo( button1, "Click" ) because of input with string name of events. Is there some other way how to get 100% correct name of event or reference to EventInfo or delegate to add_/remove_ metod of event? Some AOP way or something other?Thanks
TcKs
@TcKs - not really. Options: (1) use an interface to expose your event, and cast to that interface; (2) (only applies to `*Changed`) use abstraction such as `PropertyDescriptor` which can map properties to matching events on your behalf; (3) live with the strings (with some unit tests). I think we'd all love the missing `infoof` operator here, but it doesn't exist. We keep asking...
Marc Gravell
Thanks for suggestions.
TcKs
+1  A: 

Yes, it's just like getting the property name, but you must do it in the class that defines the event.

public class Foo
{
    public event EventHandler Bar;

    public string BarName
    {
        get
        {
            return this.GetEventName(() => this.Bar);
        }
    }

    private string GetEventName(Expression<Func<EventHandler>> expression)
    {
        return (expression.Body as MemberExpression).Member.Name;
    }
}

Enjoy.

Enigmativity
If I understand right, in this case is "this.Bar" accepted as field, isn't? It will works same with "public event EventHandler Bar" and "public EventHandler Bar", right?This is not usefull for my purpose (I'm using 3rd party classes), but It can be workaround in some cases. Thanks for reply!(+1)
TcKs
Yes, I'm afraid you're right. You can only use this approach in the class that defines the event.
Enigmativity