So I have been doing a lot of software development recently for an assignment I have at University and one thing I would like to share with you is my thoughts on Overriding the ToString method for most of your classes/objects that you create.
I think it is a very good idea to override it because you don't have to worry about creating a string, concatenating it with all the pulled properties and then output it. I'll show you an example.
Take an object of Name:
public class Name {
// Fields
private string _firstName;
private string _lastName;
// Constructor
public Name(string fName, string lName)
{
_firstName = fName;
_lastName = lName;
}
// Properties
public FirstName { get { return _firstName; } }
public LastName { get { return _lastName; } }
}
Now if you wanted to output that to a console and format it specifically as well, it could get a bit tedious:
public static void Main()
{
// Create a new Name object.
Name name =
new Name
("Charlie",
"Baker");
// Output it to a console.
Console.WriteLine(name.FirstName + " " + name.LastName);
// Outputs "Charlie Baker"
}
Now this is only a simple example and you could argue that it may not be needed due to the size of the object and its simplicity, however when you start creating more objects that incorporate each other then it can get a bit annoying to have to do this each time.
If we just override and add the ToString() method to the Name class, we can format it in there however we want and any classes that use it to output or write to the console can just output it how you want. This also makes it a lot easier to change how it is outputted later down the road if needed.
public override string ToString()
{
return _firstName + " " + _lastName;
}
Now instead of formatting it in the main method, we can just output it and not have to worry about it:
public static void Main()
{
// Create a new Name object.
Name name =
new Name
("Charlie",
"Baker");
// Output it to a console.
Console.WriteLine(name);
// Outputs "Charlie Baker"
}
You can even go further and loop through a list and produce one string that can be outputted simply and easily without having to have special display methods for that particular class.
November 6th, 2009 - No Comments - Read Article / Comment »