❔ What of use is the keyword "event"

The essence of the event field is just an object of delegate type which will invoke embedded methods when it is invoked like a method, coding below is also ok:
c#
using System;

class A
{
public delegate void F(int x, int y);
static public /*Event*/ F Event;

public static void Hi()
{
Event(1, 2);
}
}

class B
{
internal void Print(int x,int y)
{
Console.WriteLine(x + y);
}
}

public class Test
{
static void Main()
{
B suck = new B();
A.Event += suck.Print;
A.F x = new A.F(suck.Print);
A.Hi();
x(1, 2);
}
}
c#
using System;

class A
{
public delegate void F(int x, int y);
static public /*Event*/ F Event;

public static void Hi()
{
Event(1, 2);
}
}

class B
{
internal void Print(int x,int y)
{
Console.WriteLine(x + y);
}
}

public class Test
{
static void Main()
{
B suck = new B();
A.Event += suck.Print;
A.F x = new A.F(suck.Print);
A.Hi();
x(1, 2);
}
}
So the question comes.
7 Replies
Kouhai
Kouhai16mo ago
Is your question why use events instead of just using delegates?
thirteenbinary
thirteenbinary16mo ago
Yeah
Kouhai
Kouhai16mo ago
An event limits who can call the delegates. Basically only the publisher can call/raise the event
public class Foo {
public static event Action MyEvent;
public void M() {
MyEvent();
}
}

public class Bar {
public void N() {
Foo.MyEvent();
}
}
public class Foo {
public static event Action MyEvent;
public void M() {
MyEvent();
}
}

public class Bar {
public void N() {
Foo.MyEvent();
}
}
This won't compile Because Bar can only subscribe to the event, it can't raise it Other limits are you can only subscribe/unsubscribe from outside the publisher, you can't really set MyEvent to null for example Yes you can set it to null in the publisher
thirteenbinary
thirteenbinary16mo ago
So the difference between the delegate object and the event object is whether it can be raised outside the type.
Kouhai
Kouhai16mo ago
Yes, events are like a special delegates that can't be raised nor set outside of the type/derived type.
thirteenbinary
thirteenbinary16mo ago
Thank u
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.