Menu

Understand extension methods

asy proger

There are many ressources on the net explaining "generic C# extension methods".

The method On<T> tests any object derived from WcfMessage for a given message type <T>.
When the type fits, a method is called through delegate "onResponse".

In C#, extension methods of all static classes of all used namespaces are available.

namespace SourceForge.AsyncWcfLib {
  public static class WcfExtensionMethods {

    public static WcfMessage On<T> (this WcfMessage response, 
                                         Action<T>  onResponse) where T: WcfMessage
    {
      if (response != null)
      {
        T   rsp = response as T;
        if (rsp == null)
        {
          return response; // call next On extension method
        }
        onResponse (rsp);  // handle the response
      }
      return null; // already handled
    }
}}

On<T> is chainable, as its output is the same WcfMessage as its input, as long as the message has not been handled.
After the WcfMessage has been handeled, On<T> returns a null reference.
Extension methods may be called on null references without an error.

On<T> is helpful to lookup a certain received messagetype. You reduce the amount of source code for downcasting and referencing the concrete message type.

if (response.On<WcfIdleMessage>  ( HandleIdleMessage  )
            .On<WcfErrorMessage> ( HandleErrorMessage )
            .On<...>             ( Handle ... ) != null )
{
  HandleUnknownMessage ( response );
}

Any of the message handlers must have its messagetype as a single parameter and return void:

void HandleIdleMessage (WcfIdleMessage idle)
{
  ...
}

Instead of implementing a handler method, you may use a lambda expression as delegate parameter, see [Understand lambda expressions].

[Implement a client using AsyncWcfLib] shows an example using On<T> directly in the SendOut() method to handle asynchronous responses to the sent request.


Related

Wiki: Home
Wiki: Implement a client using AsyncWcfLib
Wiki: Understand lambda expressions

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.