Search code examples
c#stylecop

Custom Stylecop rule to ensure use of format specifier for the double convertions


How can i write a custom stylecop rule to ensure that the double conversions use a format specifier.for example for double.Parse or double.TryParse

double val;
string str = "1.54";
double.TryParse(str, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out val);

Solution

  • That sounds like a FxCop rule, not StyleCop. Core difference is that FxCop works with compiled assembly and has all information about the types, but does not know about source code. StyleCop works with parsed C# code (not even compiled), but knows everything about source code (and can watch your indentations, for example).

    That is why StyleCop is better for answering the question "How it is written", and FxCop is for "What is written".

    Regarding your question, in StyleCop you can find all expressions in the source file. Then filter out method invocation expressions only. Then filter method invocations named "TryParse". Then you would check that invocation target is "double" or "Double" and can check invocation parameters.

    By my advice would be - do not do that. As you can understand, there could be tons of examples when your StyleCop rule will fail. For example, one can create an alias (using D = System.Double;), pointing to double, and you will not be able to catch this.