added null reference check.
added class check before casting.