There are two methods to make it work. First one as Ryan has mentioned in his comment to your question:
List<reservation> reservations = new List<reservation>()
{
new Reservation (23,"Steve", "Jobs", 34,61,47),
new Reservation (54,"Keith", "Elliot", 45,80,23)
};
foreach (Reservation r in reservations)
{
Console.WriteLine(r.Age);
Console.Read();
}
</reservation></reservation>
However, there is another method to overcome this. That is by overriding the
ToString
function of the
object
. Each time you try to print the object the ToString function is called, in which. The only string representation of the object is its full type name. For example, your Program object if printed
Console.WriteLine(new Program());
Would print
Lecture01.Program. That is the string representation of your objects. To overcome this, you need to override the base ToString function and return your own string for each of the object instance.
Remember:
ToString is an instance function.
class Reservation {
int ResNumber;
string FirstName;
string LastName;
int RoomNum;
int Rate;
int Duration;
}
Now the function that gets called can be editted out,
public override string ToString() {
return string.Format("Property1: {0}, Property2: {1}, Property3: {2}, Property4: {3}", Property1, Property2, Property3, Property4);
}
Remember:
string.Format
is better than concatenating multiple strings.
In case where you need to get only one property, you can always call a member by object.Membername. However, in cases where you want to print the entire object. Then this would be a lot helpful as every object would be converted to this representation underground.