Search code examples
c#uwpdelegatesclone

Delegate.Clone in UWP


I'm porting an external library into my library, but its being developed under UWP environment. apparently there is no Delegate.Clone for windows 10, how can I achieve same functionality, are there any workarounds for this?

_listChanging.Clone() // list changing is instance of some delegate.
                      // unfortunately this method does not exist in UWP

Is this correct?

_listChanging.GetMethodInfo().CreateDelegate(_listChanging.GetType(), _listChanging.Target);

Solution

  • You can use the static Combine method to achieve this:

    delegate void MyDelegate(string s);
    event MyDelegate TestEvent;
    
    private void TestCloning()
    {
      TestEvent += Testing;
      TestEvent += Testing2;
    
      var eventClone = (MyDelegate)Delegate.Combine(TestEvent.GetInvocationList());
    
      TestEvent("original");
      eventClone("clone");
    
      Debug.WriteLine("Removing handler from original...");
      TestEvent -= Testing2;
    
      TestEvent("original");
      eventClone("clone");
    }
    
    private void Testing2(string s)
    {
      Debug.WriteLine("Testing2 was called with {0}", s);
    }
    
    void Testing(string s)
    {
      Debug.WriteLine("Testing was called with {0}", s);
    }
    

    Output:

    Testing was called with original
    Testing2 was called with original
    Testing was called with clone
    Testing2 was called with clone
    Removing handler from original...
    Testing was called with original
    Testing was called with clone
    Testing2 was called with clone