I've recently discovered the casting operator in C#. Now I know I can override the operator to allow either:
byte b1 = new Foo();
byte b2 = (byte) new Foo();
But from the point of view of a Foo
consumer I don't know which would be easier to understand that a conversion can be made. I'm specifically thinking on junior programmers who would/will have to maintain my code in the future (or what myself would have thought if I had seen this just some days ago).
On the one hand implicit casting looks a bit weird. It looks like assigning different, uncompatible types. And the IDE's intellisense won't tell you there's a method that can do that without the compiler complaining.
ON the other hand, explicit casting looks like forcing the conversion. Ok, it's a way of telling the compiler "I know what I'm doing, don't grumble". But how would a programmer with no access to Foo
's code (or no knowledge that casting operators exist in C#) that the casting can be performed and do something expected?
Which of the types of casting is preferred in which situations? Is there a third way?
If Foo
is obviously numeric in nature, and the conversion is widening then an implicit conversion is useful to the consumer.
If the conversion is narrowing then the operator should be explicit.
If Foo
is not numeric (and Foo
really isn't) then it should not be castable to a numeric type.
Implement some other method or property that will perform an operation to convert the Foo
instance to a numeric type. The name of that function should give semantic meaning to the caller, describing the value returned and any operation performed to return it.
You shouldn't avoid parts of a programming language because readers may not understand. You should comment your code, using simple prose, to explain your decisions and why you have made them. Explain how to use your types to their maximum advantage.
Use the features of the language that map best to the information system you are modelling. Who knows, readers might learn something.
I think, the second one is more readable in your case. The operations underlying both are the same.
Note that you could also write :
var b2 = (byte) new Foo();
which I think, would be best if readability's considered.
How? -
byte
only once.Foo
and that type of b2 is byte
in one go using (byte)
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