im trying to learn delegates and events in c#, i understand that an event is some sort of a wrapper for a delegate and a delegate is a pointer for functions/methods…
below is my code but when i run it, nothing is being shown… what could be the problems?
public class ClassHandler
{
public delegate void DoProcesses();
public event DoProcesses DoProcessesEvent;
}
public class Class1
{
public void Func1()
{
Console.WriteLine("Class 1 doing function 1");
}
public void Func2()
{
Console.WriteLine("Class 1 doing function 2");
}
}
public class Class2
{
public void Func1()
{
Console.WriteLine("Class 2 doing function 1");
}
public void Func2()
{
Console.WriteLine("Class 2 doing function 2");
}
}
class Program
{
static void Main(string[] args)
{
Class1 cs1 = new Class1();
Class2 cs2 = new Class2();
ClassHandler main = new ClassHandler();
main.DoProcessesEvent += new ClassHandler.DoProcesses(cs1.Func1);
main.DoProcessesEvent += new ClassHandler.DoProcesses(cs1.Func2);
main.DoProcessesEvent += new ClassHandler.DoProcesses(cs2.Func1);
main.DoProcessesEvent += new ClassHandler.DoProcesses(cs2.Func2);
main.DoProcessesEvent += new ClassHandler.DoProcesses(ff); // this line here is causing an error: An object reference is required for the non-static field, method, or property 'TryDelegatesAndEvents.Program.ff()'
Console.Read();
}
public void ff()
{
Console.WriteLine("gggg");
}
}
UPDATE: how do i raise the event so it will execute the methods already?
Problem with this line:
main.DoProcessesEvent += new ClassHandler.DoProcesses(ff)That is because your method
ff()is a non-static method and you can’t access it directly like that from a static method.Make your method
ffas static, or create and object of the containing class and assign the method with an instance of it.For Comments: The reason you are not seeing anything is because you are just binding them to an event
DoProcessesEvent, but you are not raising the event any where. You are only defining the handler for the event.EDIT:
Change your
ClassHandlerclass to:In your Main method before Console.Read(); Type:
This will raise the event and it will handled from the application and will give you the following output.