Creating a List<T>, issues with formatting

I'm getting all sorts of compile errors from the code below. I'm not quite sure how to Add items to a List when I have a List setups as shown below. I wan't to basically maintain the values set within the StockEntry class, and use the class StockItem as a Count. Using... _stocks.Value.Count++

public class StockEntry
{
  public string Name;
  public PeriodType Period;
  public int Min;


  public StockEntry(string Name, PeriodType Period, int Min)
  {
    this.Name = Name;
    this.Period = Period;
    this.Min = Min;
  }
}

public class StockItem<T>
{
  public T Value;

  public StockItem() {} 
  public StockItem(T val) {Value = val;}    
}

 List<StockItem<StockEntry>> _stocks = new List<StockItem<StockEntry>>();

 protected override void Initialize()
 {                                  
  _stocks.Add(new StockItem(StockEntry("ABC", PeriodType.Minute, 5)));          
  _stocks.Add(new StockItem(StockEntry("ACE", PeriodType.Minute, 5)));
  _stocks.Add(new StockItem(StockEntry("ACN", PeriodType.Minute, 5)));
 }
Jon Skeet
people
quotationmark

Aside from anything else, this could be the problem:

_stocks.Add(new StockItem(StockEntry("ABC", PeriodType.Minute, 5)));  

(and the similar lines).

StockItem is a generic class, so you need to specify the type argument:

_stocks.Add(new StockItem<StockEntry>(StockEntry("ABC", PeriodType.Minute, 5)));

If you want to avoid that somewhat redundant specification, you could create a static generic method in a non-generic type:

// Overload StockItem<T> by generic arity
public static class StockItem
{
    public static StockItem<T> Of(T item)
    {
        return new StockItem<T>(item);
    }
}

Then:

_stocks.Add(StockItem.Of(StockEntry("ABC", PeriodType.Minute, 5)));

That said, it's not really clear why StockItem needs to be generic in the first place. And I'd definitely avoid using a public field - at least make it an automatically implemented property. (Ideally IMO, make it a readonly property backed by a readonly field set in the constructor, and remove the parameterless constructor. But then I'm a fan of immutability.) Likewise I'd get rid of the public fields in StockEntry.

people

See more on this question at Stackoverflow