0

DISCLAIMER: Maybe a long explanation for a short conclusion but it's a weird situation and there are a lot of factors to reach it and I don't know if any of them has no effect on the final result, so I'm going to give all the context I can.

I'm working on a library with some misc utilities, adding some extension methods, etc...

One of the methods is defined this way:

public static class EventInfoExtensions
{
    public static void EventInfoExtensionMethod(this EventInfo ev)
    {
         //my code here
    }
}

I can use it without problems but I've came to a weird situation. First of all some context:

I have defined a DynamicObject class like this:

public class DynamicObjectBase<T> : DynamicObject
{
    public T BaseObj { get; set; }

    public DynamicObjectBase(T obj)
        : base()
    {
        this.BaseObj = obj;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        //code for getting member
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        //code for setting member
    }
}

It's been tested and working with no problems. Then I have to apply the first extension method to all the events on the BaseObj for a list of DynamicObjectBase (unknown type on runtime). Something like this:

public void ApplyToEvents(IList list)
{
     foreach(var item in list.Select(x => (x as dynamic).BaseObj))
    {
        item.GetType().GetEvents().EventInfoExtensionMethod();
    }
}

There it is. Intellisense shows the method, it builds with no errors, but if I execute the code it throws the exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Reflection.EventInfo' does not contain a definition for 'EventInfoExtensionMethod'

(translated from Spanish, may change on English)

That's the weird thing. In fact, if I try to "Go to definition" in Visual Studio it tells me it can't find the method.

I've come with this workaround and it seems to work:

public void ApplyToEvents(IList list)
{
     foreach(var item in list.Select(x => x.GetType().GetProperty("BaseObj")))
    {
        item.GetType().GetEvents().EventInfoExtensionMethod();
    }
}

Now it runs without any error and Visual Studio allows me to "Go to definition" of EventInfoExtensionMethod. The question is: Has anyone experienced this? May the "dynamic" casting be causing that?

I've been struggling with it for a few hours and the purpose of posting it there is because I don't really understand what happens and also if anyone has this problem, there's a possible workaround.

If you reached this point: thank you! :)

rualmar
  • 229
  • 2
  • 8
  • Extension methods are not supported with `dynamic` objects. – Gasper Sep 30 '16 at 18:16
  • @Gasper yes, altough extension method is not applied directly to the dynamic object, but to the EventInfo, having a dynamic source seems to be the source of the problem. – rualmar Sep 30 '16 at 19:21

0 Answers0