shujaat siddiqui
shujaat siddiqui

Reputation: 1577

Implicit and explicit casting advantages and disadvantages

I know what implicit and explicit casting are. Now I have a question for which I could not find a satisfactory answer.

  1. What are the advantages and disadvantages of implicit casting over explicit casting?

Upvotes: 2

Views: 9625

Answers (5)

Illia Tereshchuk
Illia Tereshchuk

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

BartoszKP
BartoszKP

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

Markus
Markus

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

Tal Malaki
Tal Malaki

Reputation: 422

Implicit casting must work all the time, while explicit casting might raise an exception.

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

It's pretty simple:

  • Advantage: More convenient
  • Disadvantages: More complex type system, source of bugs due to unexpected casts

Upvotes: 1

Related Questions