G
Guest
Suppose there are 2 classes A and B with a int parameter called 'val' in
each. Both of them provide a public constructor with int type parameter.
Suppose class A provides a explicit conversion operator taking B object as a
parameter and returning an A object.
A objA = new A(10);
B objB = new B(5);
objA = (A)objB; --> call public static explicit operator A(B objB) --> This
method will return "new A(objB.val)"
so now we have 2 A objects, objA is referring to A object with val = 10 and
the right side of the third statement above is returning a new A object with
val = 5. Then objA starts referring to the new A object (with val=5) and the
earlier objA (with val=10) locations are free to be garbage collected.
Instead of this - why shouldn't we have a non-static explicit conversion
operator which will replace objA.val with objB.val as a result of the
assignment and conversion?
The conversion objA = (A)objB looks similar to objA = new A(objB) -- in case
a constructor with parameter of type B is provided in class A.
Please explain the rationale behind making conversion operators static in C#
each. Both of them provide a public constructor with int type parameter.
Suppose class A provides a explicit conversion operator taking B object as a
parameter and returning an A object.
A objA = new A(10);
B objB = new B(5);
objA = (A)objB; --> call public static explicit operator A(B objB) --> This
method will return "new A(objB.val)"
so now we have 2 A objects, objA is referring to A object with val = 10 and
the right side of the third statement above is returning a new A object with
val = 5. Then objA starts referring to the new A object (with val=5) and the
earlier objA (with val=10) locations are free to be garbage collected.
Instead of this - why shouldn't we have a non-static explicit conversion
operator which will replace objA.val with objB.val as a result of the
assignment and conversion?
The conversion objA = (A)objB looks similar to objA = new A(objB) -- in case
a constructor with parameter of type B is provided in class A.
Please explain the rationale behind making conversion operators static in C#