Reputation: 163
I want to merge a DateType instance and a decimal instance into a Moving Average instance.
I created a poco file for a type MovingAverage. I use a Datetime and a decimal type
public class MovingAverage
{
DateTime Date { get; set; }
decimal Close { get; set; }
}
Below is the code that gives me an error stating that
// calculate the first SMA
for (int i = 0; i < period; i++)
{
iexTradingStock = queueCopy.Dequeue();
//if the date is the end period date, save it
if (i==(period-1))
{
MovingAverageDate = iexTradingStock.Date;
}
// add the previous moving average closing to the
// previous moving average closing
MovingAverageSum = +iexTradingStock.Close;
}
// find the simple moving average
decimal SimpleMovingAverage = MovingAverageSum/period;
// put the first SMA and date into the moving averages queue
MovingAverage mA = new MovingAverage(MovingAverageDate, SimpleMovingAverage); ---> error-MovingAverageDate is not defined
Upvotes: 0
Views: 145
Reputation: 37281
Your class MovingAverage
does not define any constructor explicitly. As such you can't initialize it like this:
MovingAverage mA = new MovingAverage(MovingAverageDate, SimpleMovingAverage);
To do so define a constructor:
public class MovingAverage
{
DateTime Date { get; set; }
decimal Close { get; set; }
public MovingAverage(DateTime date, decimal close)
{
Date = date;
Close = close;
}
}
Now the line above will compile. Other way is to define your properties as public (as it is not stated explicitly then they are currently private):
public class MovingAverage
{
public DateTime Date { get; set; }
public decimal Close { get; set; }
}
And then you can use the object initializer syntax:
MovingAverage mA = new MovingAverage {Date = MovingAverageDate, Close = SimpleMovingAverage};
As a general note, if you do not define your properties as public then consider not defining them as properties but as simple fields of the class. That is what in general is customary in C#
Upvotes: 2