'What is the purpose of using myevent(this,EventArgs.Empty)?
I am currently learning about delegates and events in csharp.I have the following set of codes:
using System;
using System.Collections.Generic;
using System.Text;
public delegate void mydel(object sender, EventArgs e);
class event1
{
public event mydel myevent;
public void onfive()
{
Console.WriteLine("I am onfive event");
Console.ReadKey();
if (myevent != null)
{
myevent(this,EventArgs.Empty);
}
}
}
public class test
{
public static void Main()
{
event1 e1 = new event1();
e1.myevent += new mydel(fun1);
Random ran = new Random();
for (int i = 0; i < 10; i++)
{
int rn = ran.Next(6);
Console.WriteLine(rn);
Console.ReadKey();
if (rn == 5)
{
e1.onfive();
}
}
}
public static void fun1(object sender, EventArgs e)
{
Console.WriteLine(" i am surplus function called due to use of '+=' ");
Console.ReadKey();
}
}
Whenever i put the following lines in comment the fun1() function is not called.Why it it so?
if (myevent != null)
{
myevent(this,EventArgs.Empty);
}
what is the purpose of these lines?
Solution 1:[1]
EventArgs : The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.
EventArgs.Empty: Used to Pass the value to event handlers that are associated with events that do not have data.
Your event is of type mydel.
public mydel myevent; // declaring an event of type mydel with signature void mydel()
Hope this might give you some spark.
Solution 2:[2]
if (myevent != null) //Checks so you instantiated a event
{
myevent(this,EventArgs.Empty); // {this} will be equal to the sender in delegete myDel, {EventArgs.Empty} is since you are not passing any arguments to your delegate.
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dah Sra |
| Solution 2 | AFract |
