Why are assignment operators not overloaded in VB.NET?

Why are assignment operators (+ =, - =, * =, / =) not overloaded in VB.NET?

+6
source share
1 answer

Perhaps this is their argument:

Thanks for the offer! We do not allow you to overload the assignment operator for a type, as there is currently no way to verify that other languages โ€‹โ€‹or the .NET Framework itself are an assignment operator. The only alternative is to limit the types that the assignment operator can overload, but we felt that it would be too restrictive to be generally useful.

Thanks! Paul Vick Technical Director, VB

There is something called โ€œNarrowingโ€ and โ€œExtensionโ€, 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 this does not allow you to change the assignment operator to assign an instance of the same class, only the conversion of 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 thing 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 }; } } 
+10
source

Source: https://habr.com/ru/post/913941/


All Articles