Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit vs explicit casting operator best practices

Tags:

c#

casting

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?

like image 523
J.A.I.L. Avatar asked Dec 25 '22 19:12

J.A.I.L.


2 Answers

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.

like image 179
Jodrell Avatar answered Dec 28 '22 10:12

Jodrell


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? -

  1. You're using byte only once.
  2. You're letting the "future programmers" know that you're casting Foo and that type of b2 is byte in one go using (byte)
like image 21
Vandesh Avatar answered Dec 28 '22 10:12

Vandesh