Friday, January 2, 2015

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.

  1. public class Country
  2.     {
  3.         private List<string> _regions = new List<string>();
  4.         public List<string> Regions { get { return _regions} set { value = _regions; } }
  5.  
  6.     }

but this is no more needed. We can simply write it as below.

  1. public class Country
  2.     {
  3.         public List<string> Regions { get; set; }=new List<string>();
  4.  
  5.     }

Also this is useful when you want to assign default values for read only fields.

Before C# 6.0

  1. public class Country
  2.   {
  3.       public string Name { get; }
  4.       public Country()
  5.       {
  6.           this.Name = "Sri Lanka";
  7.       }
  8.  
  9.   }

In C# 6.0

  1. public class Country
  2.   {
  3.       public string Name { get; }="Sri Lanka";
  4.  
  5.   }

 

This is syntactic sugar added in c# 6.0. hope this is helpful.

 

Happy Coding !!!!!!

1 comment :