Event Initializer in C# 6.0
Take the following sample class which has a property and an event listener
- public class Lecturer
- {
- public string Name { get; set; }
- public EventHandler<EventArgs> Speaking;
- }
In C# 6.0 when you initialize a new object wire up delegate to the event inside the object initialization syntax. Before C# 6.0 it was illegal.
- static void Main(string[] args)
- {
- EventHandler<EventArgs> log = (e, o) => Console.WriteLine("Speaking");
- Lecturer mathsLecturer = new Lecturer
- {
- Name = "Perera",
- Speaking += log
- };
- }
Also you can directly assign the lambda to the event as follows.
- static void Main(string[] args)
- {
- EventHandler<EventArgs> log = (e, o) => Console.WriteLine("Speaking");
- Lecturer mathsLecturer = new Lecturer
- {
- Name = "Perera",
- Speaking += (e, o) => Console.WriteLine("Speaking")
- };
- }
Happy Coding !!!
Make sense :)
ReplyDeleteThis did not make C#6 nor 7. Might want to update your post.
ReplyDelete