C #6.0 (C # vNext): Event initializers

Source: Internet
Author: User

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;


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.