A Responsive Blogger Website, That Take my blog to the next level.

I am a Software Developer, Learning and experementing with .Net Technology and try to put my Learning altogether here.


We have all sections related to .Net Technology, like .Net-C#, Asp.Net, MVC, jQuery, AngularJs, Sharepoint. Find out more...


Following are the some of the Advantages of using this Web site :-

  • Get Update about latest in .Net world.
  • Collection of Useful, Frequently used .Net Solutions.
  • It’s beautiful on every screen size (try resizing your browser!)
by

1. New Features in C# 6.0 - Auto-property initializers




In C# 6.0, a new feature has been added to set the default values of the public properties, called Auto-property initializers. Using the auto-property initializers, we can set default values to the properties without having to use a constructor.  Let us consider a simple example of the Author class as shown in the listing below:

    public class Author
    {
        public string  Name  { get; set; }
        public int Articles { get; set; } = 10;
    }

As you notice in the above listing, the default value of the Articles property is set to 10. So while creating the object, if the value of the Articles property is not set then it would be set to the default value 10. In the below listing, we are not setting the value of the Articles property of the object a, hence it is set to the default value of 10.

            Author a = new Author { Name = "Chandan" };
            Console.WriteLine(a.Name + " has authored " + a.Articles + " articles");
            Console.ReadKey(true);

The auto-property initializer sets the value of the property directly into the backing field without invoking the setters. Prior to C# 6.0, we used to create read only properties by creating a private setter and then setting the value in the constructor. However in C#6.0, using the auto-property initializer, a read only property can be easily created as shown in the listing below:

   public class Author
    {
        public string  Name  { get; set; }
        public int Articles { get; } = 10;
    }

Creating a read only property with a default value is now super easy using the Auto-property initializer, making it one of my favorite feature of C# 6.0. 

0 comments :