Last active
October 22, 2021 21:40
-
-
Save MrDave1999/a5024ac6ea3db66d1c14f538df98a066 to your computer and use it in GitHub Desktop.
Example on the use of event keyword in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ExampleEvent | |
{ | |
public class PlayerConnectedEventArgs : EventArgs | |
{ | |
public string PlayerName { get; set; } | |
public string Message { get; set; } | |
public int Id { get; set; } | |
} | |
//Publisher class | |
public class GameMode | |
{ | |
public EventHandler<PlayerConnectedEventArgs> PlayerConnectedEvent; | |
public void OnPlayerConnected(PlayerConnectedEventArgs args) | |
{ | |
PlayerConnectedEvent?.Invoke(this, args); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ExampleEvent | |
{ | |
public class MethodClass | |
{ | |
public void OnPlayerConnected(object sender, PlayerConnectedEventArgs e) | |
{ | |
Console.WriteLine($"{e.PlayerName} has joined the server!"); | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
var sample = new MethodClass(); | |
var gamemode = new GameMode(); | |
//gamemode.PlayerConnectedEvent.Invoke("", ""); --> error | |
gamemode.PlayerConnectedEvent += (sender, e) => Console.WriteLine($"{e.PlayerName} {e.Message}"); | |
gamemode.PlayerConnectedEvent += sample.OnPlayerConnected; | |
gamemode.OnPlayerConnected(new PlayerConnectedEventArgs() | |
{ | |
Id = 1, | |
PlayerName = "MrDave1999", | |
Message = "se conectó al servidor." | |
}); | |
gamemode.OnPlayerConnected(new PlayerConnectedEventArgs() | |
{ | |
Id = 2, | |
PlayerName = "Pepito", | |
Message = "se conectó al servidor." | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment