Require Interface Implementation

CJLeit

Freshman
Joined
Feb 1, 2006
Messages
32
I have 2 quick questions about interface implementation.

1. Is there a way to require someone to implement a certain interface if they inherit from my base class?

2. I have a function that the user passes a class to as a parameter. Is there a way to make sure that that the passed class implements a certain class similar to what you can do with generic functions?

Thanks!
 
If the base class implements the interface then the derived class will inherit it's implementation. If the base class is abstract (MustInherit in vb) then the derived class will be required to implement the interface.

If the function has a parameter declared as either a base class or an interface then whatever you pass in must either inherit from the base class or implement the interface - is that what you meant or are you after something different?
 
Thanks, I think the MustInherit is what I was looking for on the first questions.

On the second example right now I just have them passing an object as the parameter. Is there a way to make sure that object implements a certain interface.
 
Just for future reference, I believe you can also use the TypeOf...Is operator to see if an object is an instance of a class or interface, as in:
Code:
[Color=Blue]Public Function[/Color] IsDisposable(o [Color=Blue]As [/color][Color=DarkRed]Object[/Color]) [Color=Blue]As[/color] [Color=DarkRed]Boolean[/Color]
    [Color=Blue]Return[/Color] ([color=blue]TypeOf [/Color]o [Color=Blue]Is[/Color] [Color=DarkRed]IDisposable[/color])
[Color=Blue]End Function[/Color]

If you need code to be more dynamic, you can use reflection.
Code:
[Color=Blue]Function [/Color]DynamicTypeCheck([Color=Blue]ByVal [/Color]o [Color=Blue]As[/color] [Color=DarkRed]Object[/Color], [Color=Blue]ByVal [/Color]t [Color=Blue]As[/color] [Color=DarkRed]Type[/Color]) [Color=Blue]As[/color] [Color=DarkRed]Boolean
[/Color]    [Color=Blue]Return [/Color]t.IsInstanceOfType(o)
[Color=Blue]End Function[/Color]
 
[Color=Green]' Code Example[/Color]
MessageBox.Show(DynamicTypeCheck(someObject, [Color=Blue]GetType[/Color]([Color=DarkRed]IDisposable[/Color])))
 
Back
Top