title: How to return a value from a foreach loop of a collection?
body: <p>I have two classes <code>Invoice</code> and <code>InvoiceProducts</code>. <code>InvoiceProducts</code> is a collection and has a get only property called <code>Price</code> and I want <code>Invoice</code> to have a property called <code>TotalPrice</code> which would return the <code>Price</code> foreach item in the <code>InvoiceProducts</code> collections added to it. However I'm not sure about going about this. With the current way I'm trying to use it I get an error saying </p>
  
  <blockquote>
    <p>"Object reference not set to an instance of an object." Is there a way to do this?</p>
  </blockquote>
  
  <p>Current way:</p>
  
  <pre><code>public class Invoice
  {
      public int InvoiceID { get; set; }
      public string ClientName { get; set; }
      public DateTime Date { get; set; } = DateTime.Today;
      private decimal totalPrice;
      public decimal TotalPrice {
          get
          {
              return totalPrice;
          }
          set
          {
              foreach(var item in InvoiceProducts)
              {
                  totalPrice += item.Price;
              }
          }
      }
  
      public virtual ICollection&lt;InvoiceProducts&gt; InvoiceProducts { get; set; }
  }
  
  public class InvoiceProducts
  {
      public int InvoiceProductsID { get; set; }
      public int InvoiceID { get; set; }
      public int ProductID { get; set; }
      public int ProductQuantity { get; set; }
      public decimal Price { get { return Product.ProductPrice * ProductQuantity; } }
  
      public virtual Invoice Invoice { get; set; }
      public virtual Product Product { get; set; }
  }
  </code></pre>