Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading in .NET

In what situations would you consider overloading an operator in .NET?

like image 800
Antony Delaney Avatar asked Sep 09 '09 11:09

Antony Delaney


People also ask

What is operator overloading with example?

This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

Is there operator overloading in C#?

A user-defined type can overload a predefined C# operator. That is, a type can provide the custom implementation of an operation in case one or both of the operands are of that type. The Overloadable operators section shows which C# operators can be overloaded.

Is operator overloading polymorphism C#?

Operator overloading is an example of static polymorphism. You can leverage operator overloading or to add functionality to operators so as to work with user defined types much the same way you work with fundamental data types.


1 Answers

  • I would strongly consider overloading == and != anywhere I override Equals
  • I would consider (much less strongly) overloading comparison operators anywhere I implement IComparable<T>
  • I would consider overloading arithmetic operators for fundamentally numeric types
  • I would consider providing explicit conversions for "wrapper" types (like Nullable<T>)
  • I would very rarely consider providing implicit conversions

The golden rule is not to overload operators if the meaning isn't entirely obvious. For example, I think it would be pretty odd to have a + operator on Stream - it could mean "make a writable T here, so that writes to the result write to both" or it could mean "read one after the other" or probably other things.

In my experience it's pretty rare to overload anything other than == and !=.

like image 181
Jon Skeet Avatar answered Oct 26 '22 08:10

Jon Skeet