InterviewSolution
| 1. |
Why Should You Override The Tostring() Method? |
|
Answer» All TYPES in .Net inherit from SYSTEM.object directly or indirectly. Because of this inheritance, every type in .Net inherit the ToString() method from System.Object class. Consider the example below. using System; In the above example Number.ToString() method will correctly give the string representaion of int 10, when you call the ToString() method. If you have a Customer class as SHOWN in the below example and when you call the ToString() method the OUTPUT doesnot make any sense. Hence you have to override the ToString() method, that is inherited from the System.Object class. using System; The code sample below shows how to override the ToString() method in a class, that would give the output you want. using System; Conclusion : If you have a class or a struct, make sure you override the inherited ToString() method. All types in .Net inherit from system.object directly or indirectly. Because of this inheritance, every type in .Net inherit the ToString() method from System.Object class. Consider the example below. using System; In the above example Number.ToString() method will correctly give the string representaion of int 10, when you call the ToString() method. If you have a Customer class as shown in the below example and when you call the ToString() method the output doesnot make any sense. Hence you have to override the ToString() method, that is inherited from the System.Object class. using System; The code sample below shows how to override the ToString() method in a class, that would give the output you want. using System; Conclusion : If you have a class or a struct, make sure you override the inherited ToString() method. |
|