0

So, I have an event called CalculateNewHeight, which I've attached to an action called OnHeightDataLoaded:

renderer.OnHeightDataLoaded += ((heightData) => CalculateNewHeight(heightData, instance));

...but ideally at this point in the code it'd return a value, rather than just call another function, for example:

int newData = renderer.OnHeightDataLoaded += ((heightData) => CalculateNewHeight(heightData, instance));

Obviously that code's wrong, but you get what I mean. Using the event more like async await. Is that possible?

Haha, I'm quite new to C#, so don't hesitate to let me know if I'm going about this all wrong.

MitchEff
  • 1,417
  • 14
  • 29
  • 3
    You're thinking about this incorrectly. An event is a way for your object to report to the world that it has done something. It doesn't care whether there is one listener, no listeners, or many listeners - that's not it's responsibility. If you're interested in the result of the registered thing then I'd suggest that you should pass that thing in to your object as a dependency on your object, and call a method on that dependency that can obviously return a value. – LordWilmore Jan 24 '18 at 11:22
  • 1
    @LordWilmore, that's not completely true. .Net sometimes use events to "get a result" (sort of) from the notified client: take as example the [KeyPress](https://msdn.microsoft.com/en-US/library/system.windows.forms.control.keypress(v=vs.110).aspx) event and the Handled property of KeyEventArgs: the sender check the value of `e.Handled` set by the client, and if true it actually "swallows" the key. I agree that is not a good practice in general, considering that sender code should be agnostic to the number o client that subscribed the event. – Gian Paolo Jan 24 '18 at 11:43
  • @GianPaolo that's a good point. Thanks for making it. – LordWilmore Jan 24 '18 at 13:39
  • 1
    Haha, I swear SO is the only place on the internet you get such friendly disagreements. Cheers guys, makes a lot of sense. – MitchEff Jan 24 '18 at 22:09

0 Answers0