Yes, we can return value from events but returned value will be available to the publisher of events.
Generally, publisher do not want any value from subscriber of event, he wants to notify subscriber, so the subscriber can perform appropriate action on the particular event. for example Button click, Button class is publisher of event and allowing subscriber to perform some action when button clicked. Yes, but if we will talk technically and tried to find out answer of question "can we return value from event so, answer will be yes. Please see below example :
namespace MyLibrary
{
///
/// This class will show us use of delegate.
///
public class ReturnValuefromEvent
{
public event LoopConditionChangingEvent LoopConditionChanging;
// This method will run loop till given condition by user and when i and conition are equal then it will ask to client, that still he wants to continue..."
// by generating events and event will return value to the publisher of event.
// hence conclusion is that event can return value back to the publisher.
public void RunLoop(int condition)
{
for (int i = 0; i <= condition; i++)
{
//here we are doing some operation like :
Console.Out.WriteLine("value of i=" + i);
if (i == condition && condition != 100)
// here we are checking if loop is reached to it's initial condition provided by user, we will ask to user are you still want to continue.
{ // and also we are setting maximum limit of loop i.e.100.
if (LoopConditionChanging != null)
{
if (LoopConditionChanging())//Callback--asking to client and if client will tell yes we will increment loop
{
condition = condition + 10;
}
}
}
}
}
}
}
user will subscribe "LoopConditionChangingEvent " which will return bool value (true or false) that publisher will use inside of loop and according to given value either loop will continue or terminated.
No comments:
Post a Comment