CJLeit Posted July 6, 2007 Posted July 6, 2007 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! Quote
Administrators PlausiblyDamp Posted July 6, 2007 Administrators Posted July 6, 2007 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? Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
CJLeit Posted July 6, 2007 Author Posted July 6, 2007 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. Quote
Administrators PlausiblyDamp Posted July 6, 2007 Administrators Posted July 6, 2007 Just declare the parameters type as the interface rather than object and it should work fine. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Leaders snarfblam Posted July 8, 2007 Leaders Posted July 8, 2007 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: [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] [/Code] 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]))) Quote [sIGPIC]e[/sIGPIC]
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.