Why are C# conversion operators static?

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#
 
P

Peter Duniho

[...]
Please explain the rationale behind making conversion operators static
in C#

Well, three things come immediately to mind, even though I have little
expertise in language design:

1) If the conversion operator is not static, and the line reads "objA
= (A)objB;", what precedent is there for the compiler grabbing the lvalue
"objA" and using that as an operand for the conversion?

2) More problematically, what if the conversion is done in a context
where there's no initial instance being replaced? What if you are passing
the result of "(A)objB" as a parameter to a function, or are using it to
initialize a variable that hasn't been set yet?

2) If "objA" is to be used as an operand for the conversion, what do
we do with all of the other fields not involved in the conversion? Isn't
it a little strange to be able to have different results from the same
conversion operation, depending on the initial state of an object that is
presumably being replaced?

The more I think about it, the more I wonder why a non-static conversion
operator would ever make sense.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top