title: MVC C# Adding items to to a List<> within foreach
body: <p>I'm working on something and while I usually have no problems with c# i've had a brain meltdown and got a bit stuck...</p>
  
  <p>Within my MVC app I have a controller which manages some markers for Google Maps (as follows)</p>
  
  <pre><code>   public ActionResult GetMarkers()
      {
          MarkerList markers = getMarkersForMap();
  
          return Json(markers, JsonRequestBehavior.AllowGet);
  
      }
  
      public MarkerList getMarkersForMap()
      {
          MarkerList ml = new MarkerList();
  
          foreach (var shop in dirRepo.getAllShops())
          {
              Marker marker = new Marker
              {
                  html = shop.ShopName,
                  lat = shop.Lat,
                  lng = shop.Lng,
                  label = shop.DirectoryID.ToString()
              };
  
              ml.markers.Add(marker); // &lt;&lt;&lt;&lt; Object ref not set to an instance of an object
  
          }
          return m;            
      }
  </code></pre>
  
  <p>I also have a Markers controller as follows: </p>
  
  <pre><code>public class MarkerList
  {
      public List&lt;Marker&gt; markers { get; set; }
  }
  
  public class Marker
  {
      public string lat { get; set; }
      public string lng { get; set; }
      public string html { get; set; }
      public string label { get; set; }
  }
  </code></pre>
  
  <p>Data is being populated in the foreach no problem, but I want to add the multiple markers into the list so I can pass them back to the calling function and carry on with displaying the results in my view page. I can add single items no problem by doing this</p>
  
  <pre><code>return new MarkerList {markers = new List&lt;Marker&gt; {marker}};
  </code></pre>
  
  <p>but how about multiple items??</p>