Printing contents of an object in C#

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am new to OO programming and learning C#. I am trying to print out the
contents of an object, but am only seeing the reference to the object. The
accounts array contains Account objects, which consist of an Id, Owner and
Balance. My code is printing out

Account Name: ass1.Account

instead of

Account Name: John Smith

// List the accounts in the account array
public void ListAccounts()
{
for (int i=0; i < 100; i++){
Console.WriteLine("Account Name: {0}", accounts);
}

How do I get the actual values from the object rather than the reference?

Alison
 
Console.Writeline internally calls the ToString method of an object. The
default implementation simply returns the class name. You should override it
in your account class and return the name of the owner.

Niki
 
please post the code that puts the values in accounts[], so we can get a
clue on how to help you.
 
I worked it out late last night. I needed to add get properties to the
Account object, and then access the object properties:

public int AccountId
{
get{return Id;}
}
public string AccountName
{
get{return Owner;}
}
public long AccountBalance
{
get{return Balance;}
}

Then access those properties:

public void ListAccounts(int AccountNumber)
{
for (int i=0; i < (AccountNumber -1); i++){
Console.WriteLine("ID: {0}", accounts.AccountId);
Console.WriteLine("Name: {0}", accounts.AccountName);
Console.WriteLine("Balance: {0}", accounts.AccountBalance);
}
}

Thanks for the help.

Alison
 
Back
Top