Reputation: 167
I'm new to this so the simpler, the better. I created a class that holds details of an item such as the item name, price and description. I created a constructor so that I could initialize the object upon creation.
class Item
{
string itemName;
double price;
string description;
public Item(string itemName, double price, string description)
{
this.itemName = itemName;
this.price = price;
this.description = description;
}
}
In the main class, I created a List
of objects and two objects of that class. Then I added both objects in the List
. How can I display each object and it's values? I tried to use foreach but I can't figure out how.
static void Main(string[] args)
{
Item item1 = new Item("Ball", 9.99, "This is a ball");
Item item2 = new Item("Toy Car", 20.00, "This is a toy car");
List<Item> items = new List<Item>();
items.Add(item1);
items.Add(item2);
foreach (Item s in items)
{
Console.WriteLine(s);
}
}
Upvotes: 0
Views: 2019
Reputation: 261
Something like that for public fields:
foreach (Item s in items)
{
Console.WriteLine("{0} {1} {2}", s.itemName, s.price, s.description);
}
Or you can override ToString() method:
class Item
{
/// your code
public override string ToString()
{
return string.Format("{0} {1} {2}", itemName, price, description);
// or in C# 6 in Visual Studio 2015:
// return $"{itemName} {price} {description}";
}
Upvotes: 4
Reputation: 39976
You can override the ToString
method for this purpose like this:
public override string ToString()
{
return string.Format("itemName = {0} , price = {1} , description = {2}", itemName, price, description);
}
Or even better with string interpolation like this (c# 6):
public override string ToString()
{
return $"itemName = {itemName} , price = {price} , description = {description}";
}
Upvotes: 1
Reputation: 7009
Just override ToString
to get the string output you need.
public override string ToString()
{
return string.Format("{0}{1}{2}", itemName, price, description);
}
Upvotes: 1