C# There should be a rule for using TryAdd(), TryParse() etc. and not checking the results

  • description of the Rule answering to the question “why?”

When using TryAdd() / TryParse() you are normally doing so to avoid an exception being thrown in the case of failure. It is normally an error to ignore this return value since a user typically wants to know if the Add / Parse succeeded. If this return value is not checked, the error is silently ignored.

  • snippet of Noncompliant Code:
var myDictionary = new Dictionary<string, string>();
myDictionary.TryAdd("someKey", "someValue");
  • snippet of Compilant Code (fixing the above noncompliant code)
var myDictionary = new Dictionary<string, string>();
if (myDictionary.TryAdd("someKey", "someValue"))
{
  // Handle the failure to add here, e.g. by logging
}
  • type : Code Smell
  • silent-failure / hidden-error, bad-practice

Thank you, @BogusDude, for this rule suggestion, and apologies for the late reply.

For TryGet that would make sence, and may for TryAdd as well, but TryParse would lead to a lot of false positives:

Guid.TryParse(input, out var id);

Is perfectly valid. if you want to raise on a not provided id, or just want to deal with Guid.Empty as a special case, is up to the developer. I’m pretty sure, that I would disable this rule right away, if TryParse was included.