Pattern to use a delegate as argument in a library

I am designing a .Net library where some methods take delegates as arguments.  This situation also occurs in base class libraries with for example (amoung many others):
Sometime the design requires a parameter (like ThreadPool.QueueUserWorkItem), sometimes no parameter can be provided (the two others). Actually, I am not to sure about such design. Basically, I feel that those designs are rather arbitrary. Ad hoc objects are introduced (the delegates) but without really enabling any additionnal functionnality.

For my own needs, I have opted (this point was evocated in a previous post) for the following design



public void Foo(MulticastDelegate target, params object[] args)
{ /* snipped */ }

 

For the client, this design is much more flexible because it does not constrains the signature of the called method. A minor drawback of this approach is that there is no compile-time type check, but anyway, if there is an error, it will be detected on the first run.
For the library designer, there is no design overhead. In term of performance, I guess that there is also a slight overhead, but insignificant compared by the operation performed by Thread or AppDomain.

When I am using the .Net base library, I end up often in workarounds to achieve what would be straightforward with the design here above. I would trully like to see some refactoring of .Net in this domain.

Joannes



Answer this question

Pattern to use a delegate as argument in a library

  • Steve Whitford

    While designing libraries this way does have advantages, the main issue, which you pointed out, is the lack of compile-time checking.  This makes writing code more error prone in some situations.  Additionally, programming in this way would likely be confusing to a number of users.  That being said, if there are functions which you would like to see a different set of overloads for, please post requests at: http://lab.msdn.microsoft.com/productfeedback/Default.aspx

     

    Thank you,

     Ariel Weinstein


  • Pattern to use a delegate as argument in a library