Index Initializers in C# 6

In C# 6 Indexes can be initialized easily with neat & clean code,

  1. var user = new User   
  2. {   
  3.    [1] = "[email protected]",  
  4.    [2] = "[email protected]",   
  5.    [3] = "[email protected]",  
  6.    [4] = "[email protected]",   
  7.    [5] = "[email protected]",   
  8.    UserName = "BNarayan",   
  9.    ContactNumber= "99xxxxxxxx"   
  10. }; 

Complete Code

  1. namespace IndexInitializersCSharp6  
  2. {  
  3.   
  4.     class User  
  5.     {        
  6.         public string UserName { getset; }  
  7.         private string[] EmailIds = new string[10];  
  8.         public string ContactNumber { getset; }  
  9.         public string this[int index]  
  10.         {  
  11.             set { EmailIds[index] = value; }  
  12.             get { return EmailIds[index]; }  
  13.         }  
  14.     }  
  15.     class Program  
  16.     {  
  17.         static void Main(string[] args)  
  18.         {  
  19.             var user = new User  
  20.             {  
  21.                 [1] = "[email protected]",  
  22.                 [2] = "[email protected]",  
  23.                 [3] = "[email protected]",  
  24.                 [4] = "[email protected]",  
  25.                 [5] = "[email protected]",  
  26.                 UserName = "BNarayan",                 
  27.                 ContactNumber= "99xxxxxxxx"  
  28.             };             
  29.         }  
  30.     }