Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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!

  • Administrators
Posted

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?

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted

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.

  • Leaders
Posted

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])))

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...