When you want to add different or additional functionality with the same method call. A good example would be
ToString()
. When you can a collection of objects that you want to display in a listbox (or other list container), you can simply override the Object.ToString() method to return the desired text, like so:
public class MyObject
{
public string DisplayName { get; set; }
public MyObject(string name)
{
DisplayName = name;
}
public override string ToString()
{
return DisplayName;
}
}
Usage:
List<MyObject> myObjects = new List<MyObject>;
listbox1.Items.AddRange(MyObjects.ToArray());
Since the
Items
collection in the listbox is an object (as opposed to a string), it will call the object's
ToString
method to get displayed text. Normally,
ToString
would return the class name of the object (in the example shown above, that would have been "MyObject". However, by overriding
ToString()
, the listbox will show the contents of the
DisplayName
property instead.