0

I made a bit of code that I use to create some objects (like DependencyProperty here) more easily, it uses an Expression so I can retrieve the property name and the return type of the property with a single lamda

public static class DependencyPropertyOf<TOwner>
{
    public static IDependencyPropertyBuilder<TOwner, TProp> From<TProp>(Expression<Func<TOwner, TProp>> propSelected)
    {
        if (propSelected.Body is MemberExpression propExp && propExp.Member is PropertyInfo propInfo)
        {
            return new DependencyPropertyBuilder<TOwner, TProp>(propInfo.Name);
        }
        throw new ArgumentException("Specify a property in the expression");
    }
}

// Usage
public static readonly DependencyProperty SomethingProperty 
    = DependencyPropertyOf<MyClass>.From(myClass => myClass.Something);

I want to do the same thing but with a lambda pointing a C# event, the usage code would be

public static readonly RoutedEvent HoveredEvent =
    RoutedEventOf<MyClass>.RegisterRoutedEvent(x => x.Hovered);

public event RoutedEventHandler Hovered
{
    add => this.AddHandler(HoveredEvent, value);
    remove => this.RemoveHandler(HoveredEvent, value);
}


public static class RoutedEventOf<TOwner>
{
    public static IRoutedEventBuilder<TOwner, TProp> From<TProp>(Expression<Func<TOwner, TProp>> propSelected)
    {
        if (propSelected.Body is MemberExpression propExp && propExp.Member is PropertyInfo propInfo)
        {
            return new RoutedEventBuilder<TOwner, TProp>(propInfo.Name);
        }
        throw new ArgumentException("Specify an event in the expression");
    }

    public static RoutedEvent RegisterRoutedEvent<TProp>(Expression<Func<TOwner, TProp>> propSelected, Action<IRoutedEventBuilder<TOwner, TProp>> callback = null)
    {
        var builder = RoutedEventOf<TOwner>.From(propSelected);
        callback?.Invoke(builder);
        return builder.RegisterRoutedEvent();
    }
}

But the compiler complains that The event 'MyClass.Hovered' can only appear on the left hand side of += or -= which seems quite sensical since the compiler do a lot of extra invisible work for events I think.

So my question is: Is there a way to use Expression<> to designate events in C# ?

Related: Is it possible to target an EventHandler in a lambda expression?

Edit: Added RoutedEventOf code, so far it's basically the same as DependencyPropertyOf<> as I can't find something relevant to events in https://referencesource.microsoft.com/#System.Core/Microsoft/Scripting/Ast/LambdaExpression.cs,51d6d604b8c53dc8

Uwy
  • 457
  • 7
  • 13
  • The "related`" question you linked at the bottom of your answer makes it pretty clear that this isn't possible. – Bradley Uffner Sep 28 '17 at 14:15
  • I'm looking for any workaround that would give me type info and event name in the same fashion with minimal syntax required for usage, may it not use Expressions – Uwy Sep 28 '17 at 14:23

0 Answers0