What is “Best Practice” For Comparing Two Instances of a Reference Type?

Implementing equality in .NET correctly, efficiently and without code duplication is hard. Specifically, for reference types with value semantics (i.e. immutable types that treat equvialence as equality), you should implement the System.IEquatable<T> interface, and you should implement all the different operations (Equals, GetHashCode and ==, !=). As an example, here’s a class implementing value equality: … Read more

Arithmetic operator overloading for a generic class in C#

I think the best you’d be able to do is use IConvertible as a constraint and do something like: public static operator T +(T x, T y) where T: IConvertible { var type = typeof(T); if (type == typeof(String) || type == typeof(DateTime)) throw new ArgumentException(String.Format(“The type {0} is not supported”, type.FullName), “T”); try { … Read more

Why must the copy assignment operator return a reference/const reference?

Strictly speaking, the result of a copy assignment operator doesn’t need to return a reference, though to mimic the default behavior the C++ compiler uses, it should return a non-const reference to the object that is assigned to (an implicitly generated copy assignment operator will return a non-const reference – C++03: 12.8/10). I’ve seen a … Read more

Should operator

The problem here is in your interpretation of the article you link. Equality This article is about somebody that is having problems correctly defining the bool relationship operators. The operator: Equality == and != Relationship < > <= >= These operators should return a bool as they are comparing two objects of the same type. … Read more

How should I write ISO C++ Standard conformant custom new and delete operators?

Part I This C++ FAQ entry explained why one might want to overload new and delete operators for one’s own class. This present FAQ tries to explain how one does so in a standard-conforming way. Implementing a custom new operator The C++ standard (§18.4.1.1) defines operator new as: void* operator new (std::size_t size) throw (std::bad_alloc); … Read more