Click here to Skip to main content
15,890,995 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
anyone know how and where we can use the method overriding. can anyone give critical example of method overriding.. i mean in what situation we have to use the overriding ??/

Thanks
Rakesh
Posted

1 solution

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:

C#
public class MyObject
{
    public string DisplayName { get; set; }

    public MyObject(string name)
    {
        DisplayName = name;
    }

    public override string ToString()
    {
        return DisplayName;
    }
}

Usage:

C#
List<MyObject> myObjects = new List<MyObject>;

// populate the collection, and then do this:
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.
 
Share this answer
 
Comments
LanFanNinja 9-Dec-11 18:19pm    
+5 Good answer.
[no name] 10-Dec-11 11:48am    
5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900