Event Initializer in C# 6.0

 

Take the following sample class which has a property and an event listener

  1. public class Lecturer
  2.     {
  3.         public string Name { get; set; }
  4.         public EventHandler<EventArgs> Speaking;
  5.  
  6.     }
.

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.

  1. static void Main(string[] args)
  2.       {
  3.           EventHandler<EventArgs> log = (e, o) => Console.WriteLine("Speaking");
  4.  
  5.           Lecturer mathsLecturer = new Lecturer
  6.           {
  7.               Name = "Perera",
  8.               Speaking += log
  9.           };
  10.       }

Also you can directly assign the lambda to the event as follows.

  1. static void Main(string[] args)
  2.         {
  3.             EventHandler<EventArgs> log = (e, o) => Console.WriteLine("Speaking");
  4.  
  5.             Lecturer mathsLecturer = new Lecturer
  6.             {
  7.                 Name = "Perera",
  8.                 Speaking += (e, o) => Console.WriteLine("Speaking")
  9.             };
  10.         }

 

Happy Coding !!!

Comments

Post a Comment

Popular posts from this blog

Responsive Web Design

Affine Cipher in C#

Contract First Development in WCF 4.5