- Introduction to C# Events
- Occasions in C#
- Pronounce an Event
- Model: Declaring an Event
- Model: Raising an Event
- Sentence structure of Delegates
- Model: Consume an Event
- Model: EventHandler
- Central issues about the Events
- Passing an Event Data
- Conclusion
- An occasion is a warning conveyed by an item to message the event of an activity. Occasions in .NET follow the spectator configuration design.
- The class who raises occasions is called Publisher, and the class who gets the notice is called Subscriber. There can be numerous endorsers of a solitary occasion. Ordinarily, a distributer raises an occasion when some activity happened. The endorsers, who are keen on getting a notice when an activity happened, should enlist with an occasion and handle it.
- In C#, an occasion is an embodied representative. It is reliant upon the agent. The agent characterizes the mark for the occasion overseer strategy for the endorser class.
- Affirmation of the Event
- public occasion CellEventHandler CellEvent;
- Invokation of the Event
- on the off chance that (CellEvent != invalid) CellEvent(this, e);
- We can summon the Event just from inside the class where we pronounced the Event.
- Attaching the Event
- OurEventClass.OurEvent += new ChangedEventHandler(OurEventChanged);
- Disengage the Event
- OurEventClass.OurEvent – = new ChangedEventHandler(OurEventChanged);
- Delegates fill in as pointer to a capacity. It is a reference information type and it holds the reference of the strategy.
- System.Delegate class certainly inferred every one of the representatives.
- Agent can be pronounced utilizing the representative watchword which is trailed by the mark
- Public representative void Notify();//delegate public class ProcessBusinessLogic { public occasion Notify ProcessCompleted;//occasion
- In the above model, we announced a representative Notify and afterward pronounced an occasion ProcessCompleted of agent type Notify utilizing “occasion” catchphrase in the ProcessBusinessLogic class.
- Hence, the ProcessBusinessLogic class is known as the distributer. The Notify delegate indicates the mark for the ProcessCompleted occasion overseer.
- It indicates that the occasion overseer technique in endorser class should have a void return type and no boundaries.Presently, we should perceive how to raise the ProcessCompleted occasion. Think about the accompanying execution
- public representative void Notify();
- //delegate public class ProcessBusinessLogic { public occasion Notify ProcessCompleted;
- //occasion public void StartProcess()
- {
- Console.WriteLine(“Process Started!”);
- //some code here.. OnProcessCompleted();
- }
- secured virtual void OnProcessCompleted()
- //ensured virtual technique
- {
- //in the event that ProcessCompleted isn’t invalid then, at that point, call delegate ProcessCompleted?.Invoke();
- } }
- class Program { public static void Main()
- {
- ProcessBusinessLogic bl = new ProcessBusinessLogic(); bl.ProcessCompleted += bl_ProcessCompleted;
- //register with an occasion bl.StartProcess();
- }
- //occasion overseer public static void bl_ProcessCompleted()
- {
- Console.WriteLine(“Process Completed!”);
- }
- }
- class Program
- {
- public static void Main()
- {
- ProcessBusinessLogic bl = new ProcessBusinessLogic();
- bl.ProcessCompleted += bl_ProcessCompleted;//register with an occasion bl.StartProcess();
- }
- //occasion controller public static void bl_ProcessCompleted(object shipper, EventArgs e)
- { Console.WriteLine(“Process Completed!”);
- }
- }
- public class ProcessBusinessLogic
- {
- //announcing an occasion utilizing worked in EventHandler public occasion EventHandler ProcessCompleted; public void StartProcess()
- {
- Console.WriteLine(“Process Started!”);//some code here..
- OnProcessCompleted(EventArgs.Empty);
- //No occasion information
- }
- secured virtual void OnProcessCompleted(EventArgs e)
- {
- ProcessCompleted?.Invoke(this, e);
- }
- }
- Most occasions send a few information to the endorsers.
- The EventArgs class is the base class for all the occasion information classes.
- NET incorporates many underlying occasion information classes like SerialDataReceivedEventArgs.
- It follows a naming example of finishing all occasion information classes with EventArgs.
- You can make your custom class for occasion information by inferring EventArgs class.
- Use EventHandler to pass information to the controller, as displayed beneath.
- an occasion bl.StartProcess();
- }
- //occasion controller public static void bl_ProcessCompleted(object shipper, bool IsSuccessful)
- {
- Console.WriteLine(“Process ” + (IsSuccessful? “Finished Successfully”: “failed”));
- }
- } public class ProcessBusinessLogic
- {
- //pronouncing an occasion utilizing worked in EventHandler public occasion EventHandler ProcessCompleted; public void StartProcess()
- {
- Attempt
- {
- Console.WriteLine(“Process Started!”); //some code here.. OnProcessCompleted(true); } catch(Exception ex) { OnProcessCompleted(false); } } secured virtual void OnProcessCompleted(bool IsSuccessful)
- {
- ProcessCompleted?.Invoke(this, IsSuccessful); } }
- An occasion is a covering around an agent.
- It relies upon the representative.
- Use “occasion” catchphrase with delegate type variable to proclaim an occasion.
- Utilize worked in delegate EventHandler or EventHandler for normal occasions.
- The distributer class raises an occasion, and the supporter class registers for an occasion and gives the occasion controller strategy.
- Name the technique which raises an occasion prefixed with “On” with the occasion name.
- The mark of the controller strategy should match the agent signature.
- Register with an occasion utilizing the += administrator.
- Withdraw it utilizing the – = administrator. Can’t utilize the = administrator.
- Pass occasion information utilizing EventHandler.
- Determine EventArgs base class to make custom occasion information class.
- Occasions can be pronounced static, virtual, fixed, and theoretical.
- An Interface can incorporate the occasion as a part.
- Occasion overseers are summoned simultaneously in the event that there are different endorsers.
Introduction to C# Events :-
Occasions in C# :-
The Event is something unique that will occur. Here we will take an illustration of an occasion, where Microsoft dispatches the occasions for the designer.In this Event, Microsoft needs to mindful the designer about the element of the current or new items.
For this, Microsoft will utilize Email or other promotion choices to mindful the designer about the Event. Thus, for this situation, Microsoft will fill in as a the distributer Event and tells the designers about it.Engineers will fill in as the endorser of the Event who handles the Event.
Essentially, in C#, Events follow a similar idea. In C#, Event can be endorser, distributer, supporter, notice, and an overseer.By and large, the User Interface utilizes the occasions. Here we will take an illustration of Button control in Windows.
Button plays out different occasions like snap, mouseover, and so forth The custom class contains the Event through which we will advise the other supporter class about different things which will occur.Thus, for this situation, we will characterize the Event and illuminate different classes about the Event, which contains the occasion controller.
The occasion is an exemplified delegate. C# and .NET both help the occasions with the agents.Whenever the condition of the application changes, occasions and delegates give the notice to the customer application.
Representatives and Events both are firmly coupled for dispatching the occasions, and occasion dealing with require the execution of the agents. The sending occasion class is known as the distributer, and the collector class or taking care of the Event is known as an endorser.
Pronounce an Event :-
An occasion can be pronounced in two stages:
1. Declare a representative.
2. Declare a variable of the agent with occasion catchphrase.
The accompanying model tells the best way to pronounce an occasion in distributer class.
Model: Declaring an Event :-
Model: Raising an Event :-
Over, the StartProcess() technique calls the strategy onProcessCompleted() toward the end, which raises an occasion.
Regularly, to raise an occasion, secured and virtual strategy ought to be characterized with the name On. Secured and virtual empower inferred classes to supersede the rationale for raising the occasion. Nonetheless, An inferred class ought to consistently call the On strategy for the base class to guarantee that enlisted delegates get the occasion.
The OnProcessCompleted() strategy conjures the representative utilizing ProcessCompleted?.Invoke();. This will call all the occasion controller techniques enrolled with the ProcessCompleted occasion. The supporter class should enroll to ProcessCompleted occasion and handle it with the strategy whose mark matches Notify delegate, as displayed beneath.
Sentence structure of Delegates :-
Illustration of Delegates :
Public representative void PrintWord(int esteem); The above PrintWord representative can be utilized to point any technique which has a similar return type and proclaimed boundaries with PrintWord.
Here we will take a model that proclaims and uses the PrintWord delegates.
1. class Program1
2. {
3. //announce delegate
4. public representative void PrintWord(int esteem);
5. {
6. static void Main(string[] args)
7. {
8. //Print delegate focuses to PrintNum
9. PrintWord printDel = PrintNum;
10. {
11. //or
12. //Print printDel = new Print(PrintNumber);
13. {
14. printDel(100000);
15. printDel(200);
16. {
17. //Print delegate focuses to PrintMoney
18. printDel = PrintMoney;
19. {
20. printDel(10000);
21. printDel(200);
22. }
23. }
24. public static void PrintNum(int num)
25. {
26. Console.WriteLine(“Number: {0,- 12:N0}”,num);
27. }
28. }
29. public static void PrintMoney(int cash)
30. {
31. Console.WriteLine(“Money: {0:C}”, cash);
32. }
33. }
Yield:
In the above model, we proclaimed the PrintWord delegates, which acknowledges the int type boundary and returns the void.In the primary() strategy, we pronounce the PrintWord type technique and relegated the PrintNum name strategy.
Presently we will conjure the PrintWord delegate, which thus summons the PrintNum technique.Similarly, on the off chance that the PrintWord delegates variable is relegated to the PrintMoney strategy, this will conjure the PrintMoney technique.
Model: Consume an Event :-
Attempt it :
Over, the Program class is a supporter of the ProcessCompleted occasion.It registers with the occasion utilizing += administrator. Keep in mind, this is the same way we add strategies in the summon rundown of multicast delegate.The bl_ProcessCompleted() technique handles the occasion since it matches the mark of the Notify delegate.
Implicit EventHandler Delegate :
NET Framework incorporates worked in delegate types EventHandler and EventHandler for the most well-known occasions.Normally, any occasion ought to incorporate two boundaries: the wellspring of the occasion and occasion information.
Utilize the EventHandler delegate for everything occasions that do exclude occasion information. Use EventHandler delegate for occasions that incorporate information to be shipped off controllers.The model displayed above can utilize EventHandler delegate without announcing a custom Notify delegate, as displayed beneath.
Model: EventHandler :-
Attempt it
In the above model, the occasion controller bl_ProcessCompleted() technique incorporates two boundaries that coordinate with EventHandler delegate.
Additionally, passing this as a source and EventArgs.
Empty, when we raise an occasion utilizing Invoke() in the OnProcessCompleted() strategy. Since we needn’t bother with any information for our occasion, it simply advises endorsers about the culmination of the cycle, thus we passed EventArgs.Empty.
Central issues about the Events are :-
The central issues about the occasions are as:
1. In C#, occasion controller will accept the two boundaries as information and return the void.
2. The first boundary of the Event is otherwise called the source, which will distribute the item.
3. The distributer will conclude when we need to raise the Event, and the endorser will figure out what reaction we need to give.
4. Event can contain numerous supporters.
5. Generally, we involved the Event for the single client activity like tapping on the button.
6. If the Event incorporates the numerous supporters, then, at that point, simultaneously occasion controller summoned.
Passing an Event Data :-
Model: Passing Event Data
Attempt it :
In the above model, we are passing a solitary boolean worth to the overseers that show whether or not the interaction finished effectively.To pass more than one worth as occasion information, then, at that point, make a class getting from the EventArgs base class, as displayed underneath.
Focuses to Remember :
Conclusion :-
Delegates give a sort safe and article situated method for overseeing callbacks into techniques that have a particular mark. Circumstances that called for work pointers or callback strategies in C and C++ are ideal contender for delegates, which are type-protected and more adaptable than work pointers. Delegates utilized in C# depend on the .NET Framework’s MulticastDelegate class, which permits delegate techniques to be multiplexed into a chain of strategies that are summoned successively.
Occasions are utilized for one-way warnings between an occasion provider and a client. In spite of the fact that occasions depend on delegates, they’re not suitable for cases in which the client needs to pass a get esteem or a reference boundary once again to the provider.
At long last, ascribes give a novel way to you to definitively add usefulness to your code by enhancing your program’s components. By subclassing the System.Attribute class, you can make your own traits.