C#: Avoiding Bugs caused by not Overriding ToString

c#, tostring

Solution

By creating an override of ToString in the IntrestRate class.

Problem

I find the following bug occurring far too often in my code and wondered if anyone knows some good strategies to avoid it. Imagine a class like this: ``` public class Quote { public decimal InterestRate { get; set; } } ``` At some point I create a string that utilises the interest rate, like this: ``` public string PrintQuote(Quote quote) { return "The interest rate is " + quote.InterestRate; } ``` Now imagine at a later date I refactored the InterestRate property from a decimal to its own class: ``` public class Quote { public InterestRate InterestRate { get; set; } } ``` ... but say that I forgot to override the ToString method in the InterestRate class. Unless I carefully looked for every usage of the InterestRate property I would probably never notice that at some point it is being converted to a string. The compiler would certainly not pick this up. My only chance of saviour is through an integration test. The next time I call my PrintQuote method, I would get a string like this: "The interest rate is Business.Finance.InterestRate". Ouch. How can this be avoided?

Original source