Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / March 2008

Tip: Looking for answers? Try searching our database.

How to tell if an object inherits an interface

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Ron - 11 Mar 2008 19:34 GMT
I have a situation where I need to test if a Control implements from a
specific Interface to avoid an invalid cast exception:

foreach (Control ctrl in this.Controls)
{
// Need to test to see if ctrl inherits interface ICustomControl here
     ICustomControl control = (ICustomControl)ctrl;
}

Thanks!
Ron
Darren - 11 Mar 2008 19:40 GMT
if ( control is ICustomControl )
{
....
}

> I have a situation where I need to test if a Control implements from a
> specific Interface to avoid an invalid cast exception:
[quoted text clipped - 7 lines]
> Thanks!
> Ron
Ron - 11 Mar 2008 19:57 GMT
Thanks Darren!

> if ( control is ICustomControl )
> {
[quoted text clipped - 12 lines]
>> Thanks!
>> Ron
Andy - 11 Mar 2008 20:59 GMT
> if ( control is ICustomControl )
> {
[quoted text clipped - 12 lines]
> > Thanks!
> > Ron

Alternately, he can do this:
foreach (Control ctrl in this.Controls)
{
// Need to test to see if ctrl inherits interface ICustomControl here
ICustomControl control = ctrl as ICustomControl;
 if ( control != null ) {
   // do something
 }
}
Jon Skeet [C# MVP] - 11 Mar 2008 21:02 GMT
> Alternately, he can do this:
> foreach (Control ctrl in this.Controls)
[quoted text clipped - 5 lines]
>   }
> }

Or with C# 3 and .NET 3.5:

foreach (ICustomControl ctrl in this.Controls.OfType<ICustomControl>())
{
   ...
}

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk


Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.