Skip to main content
13 of 17
Added example of trying to use Console.WriteLine as an object
Zev Spitz
  • 693
  • 1
  • 5
  • 19

Differences between "function as first-class citizen" mechanisms

Some languages (Javascript, Python) have the notion that a function is an object:

//Javascript
var fn = console.log;

This means that functions can be treated like any other object (first-class functions), e.g. passed in as arguments to another function:

var invoker = function(toInvoke) {
    toInvoke();
};
invoker(fn); //will call console.log

Other languages (C++, C#, VB.NET) do not define functions as real objects:

//C#
var t = Console.WriteLine.GetType();
//This code will not compile, because:
//"'Console.WriteLine()' is a method, which is not valid in the given context"

Rather these languages may have objects which can point to a function (such as C++ function pointers) and can be passed around just like any other object. In the CLI, these wrapper objects are called delegates or delegate instances:

//C#
void Invoker(Action toInvoke) {
    toInvoke();
}

Action action = Console.WriteLine;
Invoker(action);

//also valid, and the toIvoke argument will now contain a pointer to Console.WriteLine
//Invoker(Console.WriteLine);

What differences in capability arise from these two mechanisms -- "function object" vs "pointer-to-function as object"?

Zev Spitz
  • 693
  • 1
  • 5
  • 19