2

How do I do the following shown in Javascript in C# 4.0:

var output = doSomething(variable, function() {
    // Anonymous function code
});

I'm sure I've seen this somewhere before but I cannot find any examples.

GateKiller
  • 74,180
  • 73
  • 171
  • 204

3 Answers3

5

Using a lambda expression (parameterless, therefore empty parentheses), it is very simple:

var output = doSomething(variable, () => {
    // Anonymous function code
});

In C# 2.0, the syntax was a bit longer:

SomeType output = doSomething(variable, delegate {
    // Anonymous function code
});
Mormegil
  • 7,955
  • 4
  • 42
  • 77
2

You'll want to look in to Lambda Expressions though it's not QUITE like JavaScript because C# works quite a bit differently. You may also want to check out delegates.

Example Code:

namespace Test {
    class Tests {
        delegate string MyDelegate();

        public void Main(string[] args) {
            var output = doSomething("test1", () => { return "test2";} );
        }

        public string doSomething(string test, MyDelegate d) {
            return test + d();
        }
    }
}
2
 var output = (x) => {
     // Anonymous function code
 };
Kris Ivanov
  • 10,476
  • 1
  • 24
  • 35