Interface at run time

  • Thread starter Thread starter fred
  • Start date Start date
F

fred

Is there a way I can find out at run time whether a particular interface has
been implemented by an instance of a class.

Thanks for any help
Fred
 
You can use the is keyword such as

dim i as IMyInterface=nothing
if(myobject is IMyInterface) then
i=DirectCast(myobject, IMyInterface)
'use the interface here...
i.MyMethod()
end if


--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
fred said:
Is there a way I can find out at run time whether a particular interface has
been implemented by an instance of a class.


Try TypeOf:

If TypeOf SomeObject Is IDisposable Then SomeObject.Dispose


LFS
 
Bob,

Bob Powell said:
You can use the is keyword such as

dim i as IMyInterface=nothing
if(myobject is IMyInterface) then

That would work in C#. For VB.NET, use 'If TypeOf ... Is ... Then...'.
 
In addition to other replies, you can also use IsAssignableFrom method of
the Type Class. Here's an example:

Public Class TestClass
Implements IDisposable

Public Sub Dispose() _
Implements System.IDisposable.Dispose

End Sub
End Class

MessageBox.Show( _
GetType(IDisposable).IsAssignableFrom( _
GetType(TestClass)).ToString)

This will return True since TestClass does implement the IDisposable
interface.

Just an additional option...


hope that helps..
Imran.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top