Skip to content

Gendarme.Rules.BadPractice.PreferTryParseRule(2.10)

Sebastien Pouliot edited this page Jan 22, 2011 · 2 revisions

PreferTryParseRule

Assembly: Gendarme.Rules.BadPractice
Version: 2.10

Description

This rule will warn you if a method use a Parse method when an alternative TryParse method is available. A Parser method, when using correctly, requires you to deal with multiple exceptions (a complete list likely not easily available) or catching all exceptions (bad). Also the throwing/catching of exceptions can kill performance. The TryParse method allow simpler code without the performance penality.

Examples

Bad example (no validation):

bool ParseLine (string line)
{
    string values = line.Split (',');
    if (values.Length == 3) {
        id = Int32.Parse (values [0]);
        timestamp = DateTime.Parse (values [1]);
        msg = values [2];
        return true;
        } else {
            return false;
        }
    }
    

Bad example (validation):

bool ParseLine (string line)
{
    string values = line.Split (',');
    if (values.Length == 3) {
        try {
            id = Int32.Parse (values [0]);
            timestamp = DateTime.Parse (values [1]);
            msg = values [2];
            return true;
        }
        catch {
            // catching all exception is bad
            return false;
        }
        } else {
            return false;
        }
    }
    

Good example:

bool ParseLine (string line)
{
    string values = line.Split (',');
    if (values.Length == 3) {
        if (!Int32.TryParse (values [0], out id))
        return false;
        if (!DateTime.TryParse (values [1], out timestamp))
        return false;
        msg = values [2];
        return true;
        } else {
            return false;
        }
    }
    

Notes

  • This rule is available since Gendarme 2.8
Clone this wiki locally