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 as
in most cases because usually if the type of the object is wrong, that indicates a bug. Bugs should cause exceptions IMO - and an InvalidCastException
at exactly the line which performs the cast is a lot clearer than a NullReferenceException
much later in the code.
as
should 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.
Not at all - it gives you the chance to verify that the conversion (cast) was done OK. If you do
TreeViewItem i = (TreeViewItem) sender;
you might get an exception if the cast fails.
Generally speaking, these two snippets are not equivalent. TreeViewItem i = sender as TreeViewItem
will yield a correct result even if sender
is a grand-grand-child of TreeViewItem
, whereas sender.GetType() == typeof(TreeViewItem)
will be true
only when sender
is precisely TreeViewItem
and none of its possible subclasses.
"as": good stuff. use it all the time.
if you really want an alternative to manually comparing types try:
if(person is Employee) { }
reads better yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With