0

I am trying to convert from a generic delegate to a named delegate.

With the result being in spirit of the following (not valid C#):

Action<CustomClass> act = ???;
CustomDelegate d = act;

I have tried

CustomDelegate d = act.Invoke;
CustomDelegate d = new CustomDelegate( act );
CustomDelegate d = new CustomDelegate( x => act(x) );
CustomDelegate d = new CustomDelegate( act.Invoke );

All of which fail at run time giving an ArgumentException with the error

Delegate to an instance method cannot have null 'this'.

The top of the stack which is not my code is:

at System.MulticastDelegate.ThrowNullThisInDelegateToInstance()

at System.MulticastDelegate.CtorClosed(object target, IntPtr methodPtr)

How to I convert a delegate such that I do not get an exception?

Community
  • 1
  • 1
vossad01
  • 11,552
  • 8
  • 56
  • 109

1 Answers1

4

I ultimately found the answer by trying @DiegoMijelshon's solution for a question on casting delegates. With that solution I got a NullReferenceException instead of the ArgumentException. Thus I found the issue was because the Action<> I had was null (it was a parameter). Thus, a null check such as the following fixed my issue.

CustomDelegate d = adt == null ? null : act.Invoke;
// Though, I actually went with @DiegoMijelshon solution to avoid extra indirection.

I then went and looked with reflector (which I should have done sooner) and found that it is indeed a null check on the parameter that causes ThrowNullThisInDelegateToInstance to be called.

Community
  • 1
  • 1
vossad01
  • 11,552
  • 8
  • 56
  • 109