Wednesday, May 22, 2013

Closure in C# versus JavaScript

Sample 1 

JavaScript

function print(s) { console.log(s); }
function sayHello(name) {

  var text = 'Hello ' + name;
  var sayAlert = function() { print(text); }
  sayAlert();
}

sayHello("Fred");

C#

static void SayHello(string name) {
    var text = "Hello " + name;
    Action sayAlert = delegate() {
        Console.WriteLine(text);
    };
    sayAlert();
}
static void Main(string[] args)
{
    SayHello("Fred");
}

Sample 2, a little more advanced 

JavaScript

function print(s) { console.log(s); }
function sayHello(name) {

  var text = 'Hello ' + name;
  return function() { 
      print(text); 
  }
}

sayHello("Fred")();

C#

static Action SayHello(string name) {
    var text = "Hello " + name;
    return delegate() {
        Console.WriteLine(text);
    };
}
static void Main(string[] args)
{
    SayHello("Fred")();
}

No comments:

Post a Comment