Книга: C# 2008 Programmer

ToString() Method

ToString() Method

All objects in C# inherits the ToString() method, which returns a string representation of the object. For example, the DateTime class's ToString() method returns a string containing the date and time, as the following shows:

DateTime dt = new DateTime(2008, 2, 29);
//---returns 2/29/2008 12:00:00 AM---
Console.WriteLine(dt.ToString());

For custom classes, you need to override the ToString() method to return the appropriate string. Using the example of the Contact class, an instance of the Contact class's ToString() method simply returns the string "Contact":

Contact c1 = new Contact() {
 ID = 1234,
 FirstName = "Wei-Meng",
 LastName = "Lee",
 Email = "weimenglee@learn2develop.net"
};
//---returns "Contact"---
Console.WriteLine(c1.ToString());

This is because the ToString() method from the Contact class inherits from the System.Object class, which simply returns the name of the class.

To ensure that the ToString() method returns something appropriate, you need to override it:

class Contact {
 public int ID;
 public string FirstName;
 public string LastName;
 public string Email;
 public override string ToString() {
  return ID + "," + FirstName + "," + LastName + "," + Email;
 }
 //...
}

In this implementation of the ToString() method, you return the concatenation of the various data members, as evident in the output of the following code:

Contact c1 = new Contact() {
 ID = 1234,
 FirstName = "Wei-Meng",
 LastName = "Lee",
 Email = "weimenglee@learn2develop.net"
};
//---returns "1234,Wei-Meng,Lee,weimenglee@learn2develop.net" ---
Console.WriteLine(c1.ToString());

Оглавление книги

Оглавление статьи/книги

Генерация: 0.799. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз