I have the following classes:
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { set; get; }
}
public class LinqValueCalculator
{
public decimal ValueProducts(IEnumerable<Product> products)
{
return products.Sum(p => p.Price);
}
}
public class ShoppingCart
{
private LinqValueCalculator calc;
public ShoppingCart(LinqValueCalculator calcParam)
{
calc = calcParam;
}
public IEnumerable<Product> Products { get; set; }
public decimal CalculateProductTotal()
{
return calc.ValueProducts(Products);
}
}
In ShoppingCart class, there's private LinqValueCalculator calc;
from my understanding we are creating an object from that class, but how is this different than private LinqValueCalculator calc = new LinqValueCalculator();
Which one should be preferred...where and why?
In ShoppingCart class, there's private LinqValueCalculator calc; from my understanding we are creating an object from that class
No, it doesn't. It declares a variable of that type, but it doesn't create any objects. Initially, that will default to null
... but it's important to differentiate between objects, variables and references. For example, you could have two variables but one object...
LinqValueCalculator calc1 = new LinqValueCalculator();
LinqValueCalculator calc2 = calc1;
Here both variables have the same value - which is a reference to the single object it creates.
See more on this question at Stackoverflow