Woof ... ok, let me generalize a bit:
So, in Java, you need a way to skip functions. Java does not inherently support functions as first-class citizens, and this was one of the reasons for introducing anonymous classes - packaged groups of functions that can be declared inline and passed (as interfaces) to methods / other classes that will then call these functions.
In C #, functions are first-class citizens and can be declared as Delegates , Func<>s or Action<>s . Try comparison (grades):
Some kind of Java-y construct (my Java is pretty old, so bear with me):
public interface IDoSomething { public int Return42(); public bool AmIPrettyOrNot(string name); public void Foo(); } public void Main(String[] args) { DoStuff(new IDoSomething() { public int Return42() { return 42; } public bool AmIPrettyOrNot(string name) { return name == "jerkimball"; } public bool Foo(int x) { ... } }); } public void DoStuff(IDoSomething something) { ... }
The (very crude) equivalent of this in C # would be:
public void Main(string[] args) { Func<int> returns42 = () => 42; Func<string,bool> amIPretty = name => name == "jerkimball"; Action<int> foo = x => {}; }
Now, as others have noted, you usually see this pattern on the Java side when dealing with events - also on the C # side:
public class Foo {
Please note that we can also give him something with the same "form":
public void MyHandler(object sender, EventArgs args) {
But it is also used in Java to determine what threads do if memory serves (i.e. Runnable ) - and we can also do this in C #:
var thread = new Thread((Action)(() => {
Now, the other things are listing:
public void processEvents(){ for(Event event : eventList) eventList.execute(); }
C # has the same idea, which is simply called otherwise:
public void processEvents() {