Ok, so maybe I\'m just tired or something but I can\'t seem to figure out why this keeps happening.
The code below is called every day for a data point in a database
You should override ToString()
for your class in format as you want, for example like this:
public class SharePrices
{
public DateTime theDate { get; set; }
public decimal sharePrice { get; set; }
public override string ToString()
{
return String.Format("The Date: {0}; Share Price: {1};", theDate, sharePrice);
}
}
By default, without overriding, ToString()
returns a string that represents the current object. So that's why you get what you described.
When you call Console.WriteLine
on a class, it will call the ToString()
method on that class automatically.
If you want to print the details out, you will over need to override ToString()
in your class, or call Console.WriteLine
with each property you want to print out.
this will work without having to use .ToString()
public class SharePrices
{
public DateTime theDate { get; set; }
public decimal sharePrice { get; set; }
}
SharePrices sp = new SharePrices() { theDate = DateTime.Now, sharePrice = 10 };
var newList2 = new List<SharePrices>();
newList2.Add(sp);
newList2.ForEach(itemX => Console.WriteLine("Date: {0} Sharprice: {1}",sp.theDate, sp.sharePrice));
C# doesn't know anything about the SharePrices
other than the class name. If you want it to display something specific, you will need to override the ToString()
method like so:
public override string ToString()
{
return "SharePrice: " + theDate.ToString() + ": " + sharePrice.ToString();
}
Of course, you can format it however you like, that is the beauty of it. If you only care about the price and not the date, only return
the sharePrice
.