Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't assignment operators overloadable in VB.NET? [closed]

Why aren't the assignment operators (+=, -=, *=, /=) overloadable in VB.NET?

like image 218
user1351569 Avatar asked Apr 23 '12 14:04

user1351569


People also ask

Can assignment operator be overridden?

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.

Why is an assignment operator 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.

Which of the operators Cannot be overload?

Dot (.) operator can't be overloaded, so it will generate an error.


1 Answers

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 };
    }
}
like image 76
Alain Avatar answered Nov 07 '22 15:11

Alain