Sunday, October 14, 2012

Collection initializer

public class Country
    {
        public int CountryId { get; set; }
        public string CountryText { get; set; }
        public List<City> Cities { get; set; }
    }



Found out some (not-so)obscure syntax allowed in C#, whereas given the above class, this is allowed, albeit has null runtime exception on Cities:


public List<Country> Countries = new List<Country>
{
 new Country 
 { 
  CountryId = 1, CountryText = "Philippines",
  Cities = 
  {
   new City { CityId = 1, CityText = "Manila" },
   new City { CityId = 2, CityText = "Makati" },
   new City { CityId = 3, CityText = "Quezon" }
  }
 }
};


Where normally, I do it as this:


public List<Country> Countries = new List<Country>
{
 new Country 
 { 
  CountryId = 1, CountryText = "Philippines",
  Cities = new List<City>
  {
   new City { CityId = 1, CityText = "Manila" },
   new City { CityId = 2, CityText = "Makati" },
   new City { CityId = 3, CityText = "Quezon" }
  }
 }
};


If you don't want to use new List<City> in collection initializer, assign it an instance first, otherwise the collection initializer would result to null runtime exception. The following could allow no new List<City> on collection initializer:

    public class Country
    {
        public int CountryId { get; set; }
        public string CountryText { get; set; }
        public List<City> Cities = new List<City>(); // instantiate List
    }

But that would break the sanctity of everything-must-be-a-property, property makes your code more future-proof

No comments:

Post a Comment