Why aren't the assignment operators (+=, -=, *=, /=) overloadable in VB.NET?
Assignment Operators Overloading in C++You can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor. Following example explains how an assignment operator can be overloaded.
Overloading assignment operator in C++ The compiler generates the function to overload the assignment operator if the function is not written in the class. The overloading assignment operator can be used to create an object just like the copy constructor.
Dot (.) operator can't be overloaded, so it will generate an error.
Perhaps this is their reasoning:
Thanks for the suggestion! We don't allow you to overload the assignment operator for a type because there is currently no way to ensure that other languages or the .NET Framework itself will honor the assignment operator. The only alternative is to restrict what types that overload the assignment operator can do, but we felt that this would be too restrictive to be generally useful.
Thanks! Paul Vick Technical Lead, VB
There's something called 'Narrowing' and 'Widening' which allows you to define explicit and implicit converters from one type to another, i.e.
Dim y as MyClass1
Dim x as MyClass2 = y
But that doesn't let change the assignment operator for assigning an instance of the same class, only converting other classes.
See How to: Define a Conversion Operator
Class MyClass1
Public Shared Widening Operator CType(ByVal p1 As MyClass1) As MyClass2
End Operator
End Class
Same in C#
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.
=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof
These operators cannot be overloaded.
With the same conversion operators:
struct MyType1
{
...
public static explicit operator MyType1(MyType2 src) //explicit conversion operator
{
return new MyType1 { guts = src.guts };
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With