Monday, February 9, 2015

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 !!!

Sunday, February 8, 2015

Dictionary Initializer in C# 6.0

 

After C# 3.0 is released we had the ability of initializing lists and dictionaries using following syntax.

  1. Dictionary<string, User> userList = new Dictionary<string, User>
  2.             {
  3.                 { "admin",new User("Sammani") },
  4.                   { "Guest",new User("Hemal") },
  5.             };

Here we add the key value pairs inside the “{ }”. In c# 6.0 it has a new syntax as follows which gives more look like working with key value pairs.

  1. Dictionary<string, User> userList = new Dictionary<string, User>
  2.           {
  3.               [ "admin"]=new User("Sammani") ,
  4.                ["Guest"]=new User("Hemal")
  5.           };

you can the number of characters are almost same in both the syntax but in c# 6.0 syntax looks more a like key value pair.

This is another syntax sugar added in c# 6.0.

Happy Coding