C# events
/* d
all the materials in this website and provided links are just for hobbies/education and there is absolutely no guarantee for any aspect of . please rethink consult . there will be no liabiloity
simple example of events in C#
*/
using System.Drawing;
using static Lib.IO;
namespace consoleapp1
{
public class ClassRoom
{
public record Student(string name, byte id);
private byte Max { get; set; } = 2;
public List<Student> ListOfStudents { get; set; } = new List<Student>();
public delegate void ListIsfullDelegate();
public event ListIsfullDelegate? ListIsfullEvent;
public ClassRoom(ListIsfullDelegate howDoYouWnatToHandle)
{
this.ListIsfullEvent += howDoYouWnatToHandle;
}
public void tryToAddItemToTheEnclosedList(Student item)
{
if (this.ListOfStudents.Count >= Max)
{
if (ListIsfullEvent != null)
ListIsfullEvent();
}
else
{
this.ListOfStudents.Add(item);
}
}
public static void Main(String[] args)
{
ClassRoom currentClassRoom = new ClassRoom(() =>
{
prompt("class room is full ... cant take more student");
});
while (UserWantsoRepeat())
{
currentClassRoom.tryToAddItemToTheEnclosedList(new Student(
prompt("enter the name of student for registration"),
byte.Parse(prompt("enter the id of student for registration"))
));
}
}
}
}
namespace Lib
{
public class IO
{
public static string prompt(string message, int delaysInMilisecon = 50)
{
message = "#: " + message + " ? ";
foreach (char c in message)
{
System.Console.Write(c);
Thread.Sleep(delaysInMilisecon);
}
Console.WriteLine();
var tempColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;
var ret = Console.ReadLine();
Console.ForegroundColor = tempColor;
return ret;
}
public static bool UserWantsoRepeat()
{
do
{
string[] yesValues = { "true", "True", "TRUE", "T", "t", "yes", "Yes", "YES", "y", "Y", "1" };
string[] noValues = { "false", "False", "FLASE", "F", "f", "yes", "No", "NO", "n", "N", "0" };
string answer = prompt("do you want to continue ");
if (yesValues.Contains(answer))
return true;
if (noValues.Contains(answer))
return false;
prompt("sorry I didn't catch that pres enter to repeat");
} while (true);
}
}
}