donderdag 30 januari 2025

C#: anonymous lambda using class instance variable

In C#, you can write an anonymous lambda which uses an instance variable of the class you are using:

Hello hello = new Hello();
hello.methodToCall((self) =>
{
    Console.WriteLine("hallo " + self.numberToReach);
});

public class Hello
{
    public int numberToReach = 3;
    public void methodToCall(Action<Hello> operation)
    {
        operation(this);
    }
}

In Kotlin, the Hello instance is bound to this, which is nice (see my trailing lambda's post). In C#, the "this" needs to be transferred using a parameter, in this case called "self".

Geen opmerkingen:

Een reactie posten