Index Initializers in C# 6

In this blog you will learn 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] = "bnarayan...@gmail.com",  
  4.    [2] = "bnarayan...@outlook.com",   
  5.    [3] = "bnarayan...@yahoo.com",  
  6.    [4] = "bnarayan...@hotmail.com",   
  7.    [5] = "bnarayan...@live.com",   
  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] = "bnarayan...@gmail.com",  
  22.                 [2] = "bnarayan...@outlook.com",  
  23.                 [3] = "bnarayan...@yahoo.com",  
  24.                 [4] = "bnarayan...@hotmail.com",  
  25.                 [5] = "bnarayan...@live.com",  
  26.                 UserName = "BNarayan",                 
  27.                 ContactNumber= "99xxxxxxxx"  
  28.             };             
  29.         }  
  30.     }