-1

Consider this code:

var someObject = GetSomeObject as ISomeInterface;    
if (someObject != null)
{ 
  // do someting, not only one method call with this object, so don't expect null propagation to be handy
  someObject.CallSomeMethod();
}

Is that preferable over this:?

var someObject = GetSomeObject();
if (someObject is ISomeInterface)
{ 
  // do someting
  ((ISomeInterface)someObject).CallSomeMethod();
}

What are the differences and when would I chose what to use?

Is it just about readability?

Mafii
  • 7,227
  • 1
  • 35
  • 55

2 Answers2

1

It makes more sense when you have more than one call.
If you need to call multiple methods, then in case 2 you will have to either:

  1. Cast it 3 times

    var someObject = GetSomeObject();
    if (someObject is ISomeInterface)
    { 
      ((ISomeInterface)someObject).CallSomeMethod1();
      ((ISomeInterface)someObject).CallSomeMethod2();
      ((ISomeInterface)someObject).CallSomeMethod3();
    }
    
  2. Declare a new casted object:

    var someObject = GetSomeObject();
    if (someObject is ISomeInterface)
    { 
      var someObjectCasted = (ISomeInterface)someObject;
      someObjectCasted.CallSomeMethod1();
      someObjectCasted.CallSomeMethod2();
      someObjectCasted.CallSomeMethod3();
    }
    

Both methods do definitely not improve code readability.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
-1

Overall, I think that when you have to explicitly cast an object to a certain type, you have to already look at your code because casting is bad practice. So I would prefer the first example.

iPhantomGuy
  • 240
  • 1
  • 11
  • 2
    "_casting is bad practice_" how comes so? – Mafii Mar 03 '17 at 08:39
  • 1
    Explicitly casting often is the cause of poor design choices in the program. It raises questions. "Why? If you really want something to be a particular type, why didn't you define it to be that type to start with?" Unless there is a specific reason you need to cast it, I would define it as a certain type, and make sure it stays that type until I have a reason to change it. But this is just my opinion, and you're free to choose. – iPhantomGuy Mar 03 '17 at 08:51
  • You confuse causation and correlation - lots of casting can be caused by poor design and can be a indication of it, but casting itself isn't bad at all. – Mafii Mar 03 '17 at 09:04
  • I would edit my original post by saying that casting without any legitimate reason is bad practice. If you have a reason, I can accept that. – iPhantomGuy Mar 03 '17 at 09:42