Search code examples
c#asp.netcompareicomparercustom-compare

Should a custom comparer for strings allow for null values


I'm looking at someone elses code for a custom comparer that compares strings.

I'm noticing that it will fall over if at least one of the string parameters is null.

The compare returns -1, 0 or 1 based on the result of the comparison.

Should code like this be fixed to handle nulls and if so what should it return if one of the parameters was null?


Solution

  • The answer will/should ultimately be a result your business requirements.

    Likely the code was written to a certain set of requirements, and nulls weren't part of the consideration.

    It should be fixed if:

    • your business requirements need it
    • you ever have the remote chance of the inputs being null
    • you're handling defects because of it
    • multiple components are leveraging this functionality