views:

57

answers:

2

Hi ,

I have the code below

RssFeedReader rss = (RssFeedReader)this.ParentToolPane.SelectedWebPart;

My problem is only at run time do I know if 'this.ParentToolPane.SelectedWebPart' is of type RssFeedReader or of type 'RssCountry'

How would I check the object type and cast it appropriatley?

Many Thanks,

+4  A: 

You can do this:

if (this.ParentToolPane.SelectedWebPart is RssFeedReader)
    //...

To check if it is of a certain type. Alternatively, you can use 'as' to use it as a type, and it will be null if it was not of that type.

RssFeedReader reader = this.ParentToolPane.SelectedWebPart as RssFeedReader;
if (reader != null)
{
    //...
}
Ryan Farley
+3  A: 

You could say

RssFeedReader rss;
rss = this.ParentToolPane.SelectedWebPart as RssFeedReader;
if(rss != null) {
    // an RssFeedReader
}

RssCountry rc;
rc = this.ParentToolPane.SelectedWebPart as RssCountry;
if(rc != null) {
    // an RssCountry
}

or

if(this.ParentToolPane.SelectedWebPart is RssFeedReader) {
    // an RssFeedReader
    RssFeedReader rss = (RssFeedReader)this.ParentToolPane.SelectedWebPart;
}

if(this.ParentToolPane.SelectedWebPart is RssCountry) {
    // an RssCountry
    RssCountry rc = (RssCountry)this.ParentToolPane.SelectedWebPart;
}

But, be warned. Almost any time that you are basing your logic on the type is a bad design smell!

Jason
Thanks i decided to create a seperate class - as it smelt bad
nav