As part of my code I have created the following struct:
struct ItemInformation
{
public int ItemNumber;
public double HighPrice, LowPrice, MedianPrice;
public ItemInformation(int number, double highP, double lowP) : this()
{
this.ItemNumber = number;
this.HighPrice = highP;
this.LowPrice = lowP;
this.MedianPrice = CalculateMedian(highP, lowP);
}
private double CalculateMedian(double high, double low)
{
return 0.5 * (high + low);
}
}
I know the struct contains four pieces of data but I want to be able to only specify three as the fourth one, MedianPrice, is completely determined by the high and low prices. So I want to use
ItemInformation jacket;
as well as
ItemInformation jacket = new ItemInformation(1234, 145.70, 73.20)
to create instances of the structure, but I cannot seem to get this to work. All the items in the struct are set correctly except for the MedianPrice. This may be a mutability issue but I am not really changing values here. I am simply setting one value based on the other two and I want to create instances of the struct using only three inputs. Does anyone have any suggestions as to how I can do this? Any advice would be greatly appreciated. Thank you.
You should make the struct immutable by making all instance fields
readonly. Also, theMedianPricecould be a property, and it needs no data in the struct value: