Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ToString Method

Status
Not open for further replies.

malola123

Technical User
Feb 16, 2007
17
CA
Hi,

Just getting familiar with the ToString method. I understand that the ToString method is used to convert the value of an object to a string type in a hopefully meaningful way. However what does this exactly mean, and during which cases can u not convert these values to a string type? Second of all, when you write:

public override string ToString()

what does the above statement exactly do?
 
ToString() is provided by the Object class, which every object (lower-case 'o') in .net ultimately inherits from. So every object gets a default implementation of ToString(), which doesn't do much useful -- just prints out the type of the object.

In order to get ToString() to do something useful, you need to replace the default functionality with your own, and the override keyword tells the compiler you're doing this. You can do pretty much anything in there, as long as you return a string.

For example, on a Customer object, you might have your implementation of ToString() return the combined first & last names:
Code:
public override string ToString()
{
   return this._firstName.Trim() + " " + this._lastName.Trim(); 
}
Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
which doesn't do much useful -- just prints out the type of the object.
Not neccesarily. While a lot of types will just spit out the type name when ToString() is called, others will convert thier value to strings. For example int's, floats, pretty much any value type. A Point will output its x and y coordinates. A lot of collection types I have seen will include the count of thier contents in the tostring output.
 
You're right -- I don't deal with value types all that often, so I forgot about those.

Not so sure about the collection types, I'll have to go look.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top