The C# is pattern, and why it beats a hard cast.

The problem
A hard cast crashes on the wrong type.
void OnHit( Component thing ){ var enemy = (Enemy)thing; // InvalidCastException enemy.TakeDamage( 10 );}
Hit a wall instead of an enemy and the cast throws.
The old fix
Cast, then check for null.
var enemy = thing as Enemy;if ( enemy != null ) enemy.TakeDamage( 10 );
Safe, but it's two steps, and enemy exists outside the if where it might be null.
The fix
Test and name it with is.
void OnHit( Component thing ){ if ( thing is Enemy enemy ) enemy.TakeDamage( 10 );}
If thing is an Enemy, it's cast and named enemy, only inside the if.
Its opposite
Bail out early with is not.
if ( thing is not Enemy enemy ) return; enemy.TakeDamage( 10 );
Return early if it's the wrong type. After the if, enemy is ready to use.
The rule
Don't cast and hope. Use is.
- Might be the type
- x is Enemy e
- Return early
- x is not Enemy e
- Hard cast
- only when certain