Is
return (T)baseAction;
the same as
return baseAction as T;
?
Is
return (T)baseAction;
the same as
return baseAction as T;
?
Yes and no
When you cast using (T)baseAction
the baseAction
must be castable to T
. If it’s not, an InvalidCastException
will be thrown.
When you cast using baseAction as T
the baseAction
does not have to castable to T
. If it’s not, the result will just be null. No exception is thrown.
Apart from that, they both do exactly the same thing: Cast one type to another
I see. So it becomes a preference between catching a null reference or invalid cast exception.
Yeah, kinda, but you can expect the null.
For instance, you can cast the sender
of an event handler to check who sent it; Assume an event comes from either a player class (Player
) or an enemy class (Enemy
). You can easily check it with
public void SomeEventHandler(object sender, EventArgs e)
{
var player = sender as Player;
if (player == null) return;
// do something with the player
}
You could of course do a check first, but that’s beyond the original post
public void SomeEventHandler(object sender, EventArgs e)
{
if (!(player is Player)) return;
var player = sender as Player;
if (player == null) return; // This shouldn't happen anymore because of the first check
// do something with the player
}
More recently these methods are becoming somewhat extinct due to changes that was made to the language. You can check and cast at the same time now
public void SomeEventHandler(object sender, EventArgs e)
{
if (!(sender is Player player)) return; // check and cast into 'player'
// do something with the player - which is in the 'player' variable
}
And @bixarrio is only showing you the Blocking versions. I prefer
if(sender is Player player)
{
// Do Something with the player which is in the player variable
}