I find that using the following:
TreeViewItem i = sender as TreeViewItem; if(i != null){ ... }
is easier to write and understand than:
if(sender.GetType() == typeof(TreeViewItem)){ TreeViewItem i = (TreeViewItem)sender; ... }
Are there compelling reasons not to use the first construct?
I prefer casts to
asin most cases because usually if the type of the object is wrong, that indicates a bug. Bugs should cause exceptions IMO – and anInvalidCastExceptionat exactly the line which performs the cast is a lot clearer than aNullReferenceExceptionmuch later in the code.asshould be used when it’s valid and legal to have been passed a reference to an object of the type that you don’t want. That situation does come up, but not as often as normal casting in my experience.Comparing types using
GetType(), however, is very rarely the right solution – it’s only appropriate when you want to check for the exact type involved rather than a compatible type.I’ve written a significantly longer answer about the ‘cast vs as’ discussion elsewhere.