Книга: 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 = "[email protected]"
};
//---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 = "[email protected]"
};
//---returns "1234,Wei-Meng,Lee,[email protected]" ---
Console.WriteLine(c1.ToString());
- 15.4 Resource Synchronization Methods
- Using Fedora's kickstart Installation Method
- 6.1.5. Trial-and-Error Method
- 8.3. Driver Methods
- Methods of Attack
- Adding Additional Test Methods
- Abstract Methods
- Virtual Methods
- Sealed Classes and Methods
- Overloading Methods
- Extension Methods (C# 3.0)
- Anonymous Methods and Lambda Expressions