Question

I recently worked with OpenTK to create small simulations and everything is running perfectly fine. The only question I have is that a statement is unfamiliar and I have never seen it in my whole programming experience. I know the functionality of the statement, but I don't understand the structure.

My "example"

Something += (parameter) =>
{
     block goes here
}

In the template

game.Load += (sender, e) =>
{
     game.VSync = VSyncMode.On;
};

The parameter gets added to the something and is all greater than the block?

Was it helpful?

Solution

This is a lambda expression, which is essentially an anonymous function. Note the "=>" vs. greater than or equal to (">="). The => operator is typically read as "goes to".

A lambda has the following form: [parameters] => {code}. The curly braces are optional; you don't need them if the lambda has only one statement. Similarly, the parens around the arguments are optional and are only needed with multiple arguments. The types of the arguments for a lambda are optional if the compiler can infer them. Here are some examples of different ways to express a simple lambda that adds 2 values:

Func<int, int, int> add = (int a, int b) => { return a + b; }
Func<int, int, int> add = (a, b) => { return a + b; } // parameter types inferred
Func<int, int, int> add = (a, b) => a + b; // curly braces optional

The other thing going on here is an event subscription, which in C# uses the += operator. By adding a lambda function to an event, we are subscribing to have that function called when the event fires. Similarly, we could subscribe a normal function to an event:

private void OnLoad(object sender, EventArgs e) { ... }

...

game.Load += this.OnLoad;

OTHER TIPS

They are called Anonymous Methods. The => is a lambda and is now the preferred way to create anonymous methods.

The (sender, e) are arguments and their types are inferred based on the signature of the delegate you are assigning to. That is to say.. if you want to know what they are, you must check the definition of the Load event on the Game type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top