C# Callable Objects

Synopsis:

A callable object is an invokeable object that can be passed to, and returned from other functions. Examples are .Net defined and custom delegates and lambdas.
A callable object has a specified signature, e.g., return type and parameter type sequence. The caller has to know the signature in order to successfully use a callable object.
Here is demonstration code that creates an invoker that accepts any of these callable objects.

Code in File CallableObjects.cs

  /////////////////////////////////////////////////////////////////////
  // CallableObjects.cs - demonstrate callable object invoker        //
  //                                                                 //
  // Jim Fawcett, CSE681 - Software Modeling and Analysis, Fall 2017 //
  /////////////////////////////////////////////////////////////////////

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;

  namespace CallableObjects
  {
    public class InvokeCallable
    {
      public void invoke(Action act)
      {
        act.Invoke();
      }
    }
    class TestCallableObjects
    {
      string msg_ = "";
      delegate void MyDelegate();

      void setMsg(string msg) { msg_ = msg; }

      void say()
      {
        Console.Write("\n  Hi from {0}", msg_);
      }
      static void Main(string[] args)
      {
        Console.Write("\n  Demonstrating Invoker of Callable Objects");
        Console.Write("\n ===========================================");

        TestCallableObjects tco = new TestCallableObjects();
        InvokeCallable ic = new InvokeCallable();

        // using method is easy

        tco.setMsg("class method");
        ic.invoke(tco.say);

        // using lambda is easy

        ic.invoke(() => Console.Write("\n  Hi from lambda"));

        // using Action delegate is easy

        tco.setMsg("Action delegate");
        Action act = tco.say;
        ic.invoke(act);

        // using custom delegate is a bit messy
        //   - uses reflection to get delegate's bound function

        tco.setMsg("custom delegate");
        MyDelegate md = new MyDelegate(tco.say);
        Type t = md.GetType();
        ic.invoke((Action)Delegate.CreateDelegate(typeof(Action), md, "Invoke"));

        Console.Write("\n\n");
      }
    }
  }

Delegates Output:

  
  Demonstrating Invoker of Callable Objects
 ===========================================
  Hi from class method
  Hi from lambda
  Hi from Action delegate
  Hi from custom delegate

Press any key to continue . . .

Example Code:


CST strip