Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there compelling reasons AGAINST using the C# keyword "as"?

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?

like image 567
Mark Carpenter Avatar asked Feb 20 '09 13:02

Mark Carpenter


4 Answers

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 NullReferenceExceptionmuch 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.

like image 88
Jon Skeet Avatar answered Sep 22 '22 21:09

Jon Skeet


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.

like image 33
Otávio Décio Avatar answered Sep 23 '22 21:09

Otávio Décio


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.

like image 22
Anton Gogolev Avatar answered Sep 22 '22 21:09

Anton Gogolev


"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.

like image 39
andleer Avatar answered Sep 24 '22 21:09

andleer