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?

Re: checking for valid cast before cast is called? by Brian

Brian
Mon Jun 27 16:29:47 CDT 2005

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

wgillin wrote:
> 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?