nav
nav

Reputation: 3

Determining casting of an object

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,

Upvotes: 0

Views: 186

Answers (2)

jason
jason

Reputation: 241601

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!

Upvotes: 3

Ryan Farley
Ryan Farley

Reputation: 11421

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)
{
    //...
}

Upvotes: 4

Related Questions