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

csharp

(Bogus) #1
  • 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