-1
using System;

namespace SampleApp {
   public delegate string MyDel(string str);
    
   class EventProgram {
      event MyDel MyEvent;
        
      public EventProgram() {
         this.MyEvent += new MyDel(this.WelcomeUser);
      }
      public string WelcomeUser(string username) {
         return "Welcome " + username;
      }
      static void Main(string[] args) {
         EventProgram obj1 = new EventProgram();
         string result = obj1.MyEvent("Tutorials Point");
         Console.WriteLine(result);
      }
   }
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
Mr.Wadile
  • 11
  • 1
  • A couple quick notes: 1- Your code does not contain `this.MyEvent += new MyDel...` but `this.MyEvent = new MyDel...`. That looks like a typo in your question. And 2- That line is where you are subscribing to the event. Because different agents can subscribe to the same event that is why yhe subscription is usually additive (used the `event += delegate` syntax). In your current code, because the event is not public, it should be fine doing an `event = delegate` (your class is the only one able to subscribe to it) – Cleptus Nov 11 '21 at 11:17
  • 2
    Where did you get this sample? It is more confusing than helpful in understanding why and when you need events. – Steve Nov 11 '21 at 11:22
  • @Steve I wonder if that code would even compile, probably needs a `public event` so others can subscribe to it. I think is far more clear the [c# reference event documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/event) – Cleptus Nov 11 '21 at 11:27
  • It compiles (at least on LinqPad) but certainly it is not very helpful as a sample on how to work with events – Steve Nov 11 '21 at 11:38
  • 1
    You probable need to know what are delegates and how are used[check this question](https://stackoverflow.com/a/1735280/2265446) or need to know what are Events and how are used [this question is usefull](https://stackoverflow.com/questions/803242/understanding-events-and-event-handlers-in-c-sharp) – Cleptus Nov 11 '21 at 11:39
  • @Steve Here i am just understanding what's role of "+= " – Mr.Wadile Nov 11 '21 at 11:51
  • 1
    @Mr.Wadile The role of `+=` when subscribing to the event is because usually the intented usage of events is "_allow everybody to subscribe to it_" and because of that the `+=` operator is used (to allow multiple subscriptions). if you only `event = function1;` and later do `event = function2;` because of the `=` usage the first function would never be called... And debugging that wrong behavior would be a pain in the ass. – Cleptus Nov 11 '21 at 11:57
  • @cleptus Thank youbsir – Mr.Wadile Nov 11 '21 at 16:15
  • Thanks every one all to sharr your view – Mr.Wadile Nov 11 '21 at 16:15
  • @all because of you all i understood this login thanks again and keep support – Mr.Wadile Nov 11 '21 at 16:16

1 Answers1

1

The idea of using events is to provide ability for some object, which stores this event (called "publisher") notify some others objects (called "subscribers"), who subscribed to this event, that something happened.

Your example may be used in a way "Notify when some user joined". It utilizes some sort of "Publisher-Subscriber pattern".

So, you have some EventProgram class, which is "publisher" that stores event OnUserJoin, which is fired every time when user joins (adds to List). Event firing provided through invoking OnUserJoin EventHandler after adding new user. When invoking it, we providing username to UserJoinedEventArgs - which are a kind of "details" of "what was happened". OnUserJoin? (with ?) means a check, that there are some "subscribers" to who we can "send notification".

public class EventProgram
{
    private readonly List<string> users;

    // Publishing event for "subscribers"
    public event EventHandler<UserJoinedEventArgs> OnUserJoin;

    public EventProgram() 
    {
        users = new List<string>();
    }

    public void AddNewUser(string username)
    {
        // Adding new user
        users.Add(username);
        // And calling event to notify "subscribers" that we added provided user
        OnUserJoin?.Invoke(this, new UserJoinedEventArgs { Username = username });
    }
}

// Custom details for our event
public class UserJoinedEventArgs
{
    public string Username { get; set; }
    // and other details you wish to provide about joined user
}

And usage of it as a "subscriber" is to create handler (HandleUserJoin in example), which will "accept notifications" from "publisher" class and do something with accepted details from UserJoinedEventArgs.

void Main(string[] args = default)
{ 
    EventProgram eventProgram = new EventProgram();
    // "Subscribing" to "publisher"'s event with `HandleUserJoin` handler
    eventProgram.OnUserJoin += HandleUserJoin;

    // Adding new user
    eventProgram.AddNewUser("Mr.Wadile");
}

// This handler is actually "subscriber", which waits for notifications
// from "publisher"'s OnUserJoin event with details, provided
// as UserJoinedEventArgs
private void HandleUserJoin(object sender, UserJoinedEventArgs args)
{
    Console.WriteLine("Welcome, " + args.Username);
} 

At result, each time when we adding new user with .AddNewUser("Some Username") - "publisher" EventProgram will notify us through OnUserJoin event and when we "accept" this notification in HandleUserJoin - we print welcome message.

Answering to question about += operator - this is actually "subscribing" process, when you "subscribing" HandleUserJoin method to notifications from OnUserJoin event (in this example).

Delegates are, in common, "pointers" to some methods, which match to delegate signature. Based on example above, you can use delegate to combine different actions and call them all as one:

public class EventProgram
{
    private readonly List<string> users;
    // Delegate declaration with "void (string)" signature
    public delegate void JoinUser(string username);

    // A field of delegate type, that will be used to call from other classes
    public JoinUser JoinNewUser;

    public EventProgram()
    {
        users = new List<string>();

        // Combining different actions with User into one delegate
        // First - assigning with "=" (+= can be used too)
        JoinNewUser = AddUserToDatabase;
        // Next - appending with "+="
        JoinNewUser += WelcomeUser;
        JoinNewUser += SendWelcomeGiftToUser;
    }

    // Matches to delegate signature "void (string)"
    private void AddUserToDatabase(string username)
    {
        users.Add(username);
        Console.WriteLine("New user \"" + username + "\" added to database!");
    }
   
    // Matches to delegate signature "void (string)"
    private void WelcomeUser(string username) =>
        Console.WriteLine("Welcome, " + username);

    // Matches to delegate signature "void (string)"
    private void SendWelcomeGiftToUser(string username) =>
        Console.WriteLine(username + ", we sending you 100$ as a welcome gift!");
}

So from other class we just call JoinNewUser after creating instance of EventProgram, and all 3 actions will be invoked by delegate:

void Main(string[] args = default)
{
    EventProgram eventProgram = new EventProgram();
    eventProgram.JoinNewUser("Mr.Wadile");
}

So it would look like:

enter image description here

The += operator is usually used when subscribing to events, because the = operator would replace the "delegates stack" and only the last delegate would be executed. For example, in the previous example:

JoinNewUser = AddUserToDatabase;
JoinNewUser = WelcomeUser;
JoinNewUser = SendWelcomeGiftToUser;

Would only output the SendWelcomeGiftToUser delegate instead of the expected three delegates/functions/methods:

Mr Wadile, we sending you 100$ as a welcome gift

Auditive
  • 1,607
  • 1
  • 7
  • 13
  • Regarding the `+=` usage, I would add that `=` could be used, but generally `+=` is used instead to allow multiple subscriptions to the same event, otherwise only the last delegate would be called when the event is triggered. Nice answer nonetheless – Cleptus Nov 11 '21 at 12:11
  • @Cleptus, I tried to show `=` / `+=` usage when describing delegates part of answer. Maybe not what you mean, so feel free to correct me. – Auditive Nov 11 '21 at 12:53
  • Edited your answer, check the edit and if you feel it is wrong or deviates from what you intented yo tell, feel free to rollback the edit/delete/correct it. – Cleptus Nov 11 '21 at 13:46
  • @Cleptus, thanks, looks like much clearer explanation now. – Auditive Nov 11 '21 at 13:48
  • thank you its help to get understand – Mr.Wadile Nov 11 '21 at 18:21