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
 
The first one will simply return null and not throw an exception if the
cast fails, while the other one will.

Thank you for the clarification
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Unable to cast object 2
Equals 3
cast 3
IList, IDictionary, ... 2
casting (best practice?) 2
about casting 24
Easy way* to cast an object in a LINQ query? Methinks not* 28
Boolean to String 2

Back
Top