1

I would like to catch all calls to decimal.ToString() in my solution. At compile time. (the question marked as "original" is about a run time solution)

Is there any trick for this? like overloading ToString and using ObsoleteAttribute?

I can resolve to running a scan (by reflection) once a week through code like this or install and configure some sort of program with static code checking. But this question is about compile time.

The reason for this is that decimal.ToString is culture aware and which in my case might be trouble; i.e. if someone installs the solution on a localised server output might change.
We have a rule not to call decimal.ToString without making it CultureInvariant but it is not always heeded.

Community
  • 1
  • 1
LosManos
  • 6,117
  • 5
  • 44
  • 81
  • 4
    You can make a Roslyn analyzer. – SLaks Aug 31 '16 at 21:24
  • 1
    There are static analysis tools that allow you to check your code against coding standards (including defining custom rules). That way you could check your code against all of your rules at once. – EJoshuaS - Reinstate Monica Aug 31 '16 at 21:30
  • @BartoszKP Quite close and might solve my problem if I relax from compile time to instead run a tool once a week. Thx. – LosManos Aug 31 '16 at 21:32
  • 2
    A Roslyn analyzer may address some of the situation, but there are lots of ways `ToString()` could be called implicitly, without any way to detect. You really need to narrow your problem, and quite possibly just forget about it. Better to create unit tests that would catch culture-dependent output of `decimal`-to-text values. – Peter Duniho Aug 31 '16 at 21:39
  • Side note: How you expect to catch `decimal.ToString()` in `String.Format("{0}", 1m)` at compile time? – Alexei Levenkov Aug 31 '16 at 21:39
  • @AlexeiLevenkov I don't. I just aim for the 99%. – LosManos Aug 31 '16 at 21:42
  • 1
    Would be interesting (mostly for entertainment purposes) to see what kind of code you hope to catch - calling `ToString` explicitly on value type feels soo rare event to me as that would be done by formatting or serialization core, like JSON.Net – Alexei Levenkov Aug 31 '16 at 21:51
  • @LosManos You can run a tool during compile time. – BartoszKP Aug 31 '16 at 21:54
  • Anyway, @PeterDuniho nailed it: good unit-tests are the best solution. – BartoszKP Aug 31 '16 at 21:55
  • 1
    @AlexeiLevenkov Good point. My main problem is that we unfortunately store decimals as strings in the database through Nhibernate. You got me thinking [x-y-problem](http://xyproblem.info) that it might be nicer to fix it there. – LosManos Sep 01 '16 at 07:02

1 Answers1

4

Microsoft's Code Analysis rules can be set to notice a variety of culture-dependent string creation issues, including the use of string.Format() and string interpolation. You can set those rules' severity to "Error" level, and then set up your project to fail a build whenever they are violated.

StriplingWarrior
  • 135,113
  • 24
  • 223
  • 283