C #6.0 (C # vNext): Event initializers
Event initializers)
The new feature in C #6.0 allows you to initialize the event processing function directly when creating an instance, as shown below:
Example 1:
new Customer { Notify += MyHandler };
Example 2:
var client = new WebClient{ DownloadFileCompleted += DownloadFileCompletedHandler};
Example 3:
var button = new Button { ... Click += (source, e) => ... ... };
In another example, initialize an event directly.
public virtual event EventArgs RoslynReleased = delegate { };
Next we will compare the original and new writing methods:
public class Person{ private int _age; public int Age { get { return _age; } set { _age = value; OnAgeChanged(EventArgs.Empty); } } public string Name { get; set; } public event EventHandler AgeChanged; protected virtual void OnAgeChanged(EventArgs e) { if (AgeChanged != null) { AgeChanged(this, e); } } public override string ToString() { return string.Format("Name:{0}, Age:{1}", Name, Age); }}
Previous writing:
var person = new Person { Age = 30, Name = "Calvin" };person.AgeChanged += (s, e) => Console.WriteLine("Person:{0}", ((Person)s));person.Age += 1;
New statement:
var person2 = new Person { Age = 30, Name = "Kelly", AgeChanged += (s, e) => Console.WriteLine("Person:{0}", ((Person)s)); };person2.Age += 1;