Cast? Which is the correct way?

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

Is there a difference between using:
controller = ObjectFactory.GetInstance(controllerType) as
IController;

Or
controller = (IController)ObjectFactory.GetInstance(controllerType);

I see the first one with a VB similar sintax and the second one as C#.
But C# accepts both ...

How should I use it?

Thank You,
Miguel
 
Hello,

Is there a difference between using:
controller = ObjectFactory.GetInstance(controllerType) as
IController;

Or
controller = (IController)ObjectFactory.GetInstance(controllerType);

I see the first one with a VB similar sintax and the second one as C#.
But C# accepts both ...

How should I use it?

Thank You,
Miguel

The first one will simply return null and not throw an exception if the
cast fails, while the other one will.
 
Is there a difference between using:
controller = ObjectFactory.GetInstance(controllerType) as
IController;

Or
controller = (IController)ObjectFactory.GetInstance(controllerType);

I see the first one with a VB similar sintax and the second one as C#.
But C# accepts both ...

How should I use it?

The first return null if cast not possible the last throw an
exception if cast not possible.

In most cases I will recommend the last, because it gives
much easier to find errors.

Arne
 
Back
Top