-
Notifications
You must be signed in to change notification settings - Fork 4
Gendarme.Rules.BadPractice.PreferTryParseRule(2.10)
Assembly: Gendarme.Rules.BadPractice
Version: 2.10
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.
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;
}
}
- This rule is available since Gendarme 2.8
Note that this page was autogenerated (3/17/2011 9:31:58 PM) based on the xmldoc
comments inside the rules source code and cannot be edited from this wiki.
Please report any documentation errors, typos or suggestions to the
Gendarme Mailing List. Thanks!