Posts

Showing posts from January, 2015

Primary Constructor in C# 6.0

  In my previous post I explain about Auto Property Initializer in C# 6.0. Now lets see another new feature in C# 6.0 which is Primary constructor. First we will see the following code. public class Country {      public string Name { get ; private set ; }        public Country( string name)          {          Name = name;          }   } here we have a class which has a property with a private setter and assigning the value for the name property inside the constructor. Now in C# 6.0 you can write the above code in a more simplified manner as follows. public class Country ( string name)      {          public string Name { get ;}=name;          } This is what is called primary constructor in C# 6.0 . Notice the parameters added just right of the class definition. This tells the compiler to add a constructor to the Country class with one parameters: name. So we don’t need to create separate constructor with par...

Auto Property Initializer

  Anyone who have worked with properties in a class must have experienced that it was little annoying that we have to have private fields and assigned if we want to have default values for properties. See the following example which we used to do when we have collection property. public class Country      {          private List < string > _regions = new List < string >();          public List < string > Regions { get { return _regions} set { value = _regions; } }        } but this is no more needed. We can simply write it as below. public class Country      {          public List < string > Regions { get ; set ; }= new List < string >();        } Also this is useful when you want to assign default values for read only fields. Before C# 6.0 public class Country    {        public string Name { get ; }        public Country()        {            this .Name = "Sri Lanka" ; ...