Maybe this will help a little in addition to OPâs example.
First, the .NET common language runtime requires that every object be derived from Sytem.Object so that every object has a ToString() method (among others). The ToString() method can be used by an object to define its own value semantics, or the object can default to System.Objectâs implementation of ToString(), which simply returns the objectâs name.
Second, the reason all objects must implement a ToString() method is because many .NET framework components need to be able to call an objects ToString() method to function correctly. OPâs Console class example is an excellent one. Another is the whole Windows Forms Data Binding subsystem.
Maybe a visual will help. Code for a simple class named Person and a simple form with a ListBox is listed below.
When you initially run the program, the ListBox displays:
Person
Person
This is because Windows Forms Data Binding automatically calls the Person object's ToString() method when the ListBox binds to the object. Since the Person class doesnât override ToString(), System.Objectâs default implementation is used, and the objectâs name is returned.
Now, override ToString() in the Person class by adding the following method:
Code:
public override string ToString()
{
return String.Format("{0}, {1}", LastName, FirstName);
}
Now the ListBox displays:
Doe, John
Doe, Jane
In other words, Windows Forms Data Binding (and many other framework components) require your objects to implement a parameterless ToString() method in order to work correctly. This âcontractâ between your objects and the Data Binding subsystem, for example, is enforced by requiring your object's to subclass System.Object.
Now, yes, you could write your own method to do the formatting ToString() overrides can do. But in doing so, you would deprive your objects of the ability to interact with framework components that require being able to make calls to a parameterless method named ToString().
Hereâs the rest of the code.
Code:
using System;
public class Person
{
public string FirstName;
public string LastName;
public Person() { }
}
Code:
using System;
using System.Windows.Forms;
public class Form1 : Form
{
private BindingSource bindingSource = new BindingSource();
private ListBox listBox1;
static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
// initialize Form.
this.listBox1 = new System.Windows.Forms.ListBox();
this.Controls.Add(this.listBox1);
// bind listbox to binding source
bindingSource.Add(new Person{ FirstName="John", LastName="Doe"});
bindingSource.Add(new Person{ FirstName="Jane", LastName="Doe"});
listBox1.DataSource = bindingSource;
}
}
HTH,
Bob