Taylor Bishop
Taylor Bishop

Reputation: 519

C++ capture-clause equivalent for anonymous lambda functions in C#

I'm currently trying to port over a project I wrote in C++ to a C# framework. I'm running into an issue with passing functions over to another class.

I have a class, PickupDef that takes a delegate function as a paremeter in its constructor. In the C++ version, I would pass over the function like so:

[&]() { hero->changeHP(10); }

Where hero is a dynamically allocated object in the calling class. I've tried using this in the C# version:

delegate { hero.changeHP(10); }

But C# doesn't recognize the hero object. It seems like I can't scope it to take in references from the calling class.

Is there a way to get the functionality of the C++ [&]() in C#? I could pass a reference to the hero object to the PickupDef but that would require an overhaul of the current system.

Upvotes: 1

Views: 280

Answers (1)

user545680
user545680

Reputation:

A lambda in C# is written like so:

() => hero.changeHP(10);

As this is a parameterless lambda, you can pass it around as an Action instance e.g.

Action setHpTo10 = () => hero.changeHP(10);

Lambdas inherently capture the variable that you are referencing in C#.

Upvotes: 3

Related Questions