Reputation: 1577
I know what implicit and explicit casting are. Now I have a question for which I could not find a satisfactory answer.
Upvotes: 2
Views: 9625
Reputation: 1202
For variables:
Implicit casting makes the developer free of mentioning the type every time. It is useful for numeric data types:
Int32 integerNumber = 20;
Decimal decimalNumber = integerNumber; //It is OK
But - you should use only explicit casting where completely different types are converted:
CustomString customString = "This is custom string";
//Int32 customStringLength = customString; //It is NOT OK
Int32 customStringLength = (Int32)customString; //It is OK
For interfaces:
interface IFooBar
{
void MakeABarrelRoll();
}
An implicit interface implementation allows all the code "seeing" its methods:
class FooBar: IFooBar
{
public void MakeABarrelRoll()
{
//Make a barrel roll here
}
}
We can call it directly from object:
FooBar foobar = new FooBar();
foobar.MakeABarrelRoll(); //Works
Explicit interface implementation makes its methods open only if object was casted to an interface explicitly.
class FooBar: IFooBar
{
public void IFooBar.MakeABarrelRoll()
{
//Make a barrel roll here
}
}
We can not call it directly from object:
FooBar foobar = new FooBar();
//foobar.MakeABarrelRoll(); //Does not work
((IFooBar)foobar).MakeABarrelRoll(); //Works
Upvotes: 1
Reputation: 35891
Implicit casting is rarely used, because it reduces readability of your code. Explicit casting is a bit more readable, but a bit less convenient.
Finally, from my experience, the most readable way is to provide ToTargetType
methods, which, beside readability when using, can be easily discovered by list of methods in the IDE (to see conversion operators you need to view the source of the class).
Upvotes: 0
Reputation: 22456
Implicit casting is more convenient as you do not have to add the explicit cast when casting. However, you might want to choose explicit casting to signal clearly to the developers that a cast is done.
Upvotes: 1
Reputation: 422
Implicit casting must work all the time, while explicit casting might raise an exception.
Upvotes: 0
Reputation: 185862
It's pretty simple:
Upvotes: 1