checking for valid cast before cast is called?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Is there a way in .net to check the validity of a cast before the cast is
actually made? My situation is I am building a ListBox that I would like to
function with either my customized objects as items or the standard ListBox
items. In order to draw my custom objects I need to cast them inside the
OnDrawItem method like this:

(WcgListBoxItem)this.Items[e.Index]

Is there any way to test what the object type of this.Items[e.Index] is
before I do the cast?
 
The "is" and "as" keywords will allow you to do this.

if (this.Items[e.Index] is WcgListBoxItem)
{
WcgListBoxItem item = (WcgListBoxItem)this.Items[e.Index];
}

or

WcgListBoxItem item = this.Items[e.Index] as WcgListBoxItem
if (item != null)
{
}

Brian
 
Back
Top