needs overload operator< and null check

后端 未结 5 1407
暖寄归人
暖寄归人 2020-12-18 21:54

I´m overloading the lessthan-operator in c# and I`m wondering whether this needs to check for null. Below you can find an Example:

public static bool operat         


        
5条回答
  •  轮回少年
    2020-12-18 22:03

    1. It's a bad idea to overload operators on classes. It's ok for structs though.

    2. If you do decide to overload an operator on a class, you will either have to:
      a. Include null-check into your logic
      b. Throw exceptions when null is passed in
      c. Don't null check and allow for NullReferenceExceptions (bad)

    Basically, it's a bad idea to overload an operator on a class. I'd either turn your class into a struct, or just implement an interface such as IComparable / IEquatable which has guidelines when null values are used in comparisons.

提交回复
热议问题