views:

1271

answers:

2

I was kind of shocked by this. Could someone explain why this works? A good example of when to use it would also be nice.

Public Interface IFoo
  Sub DoIt()
End Interface

Public Class Bar
  Implements IFoo

  Private DoIt() implements IFoo.DoIt
End Class

...

Dim b as new Bar()
b.DoIt() 'error
CType(b, IFoo).DoIt() 'no error
+2  A: 

I was kind of shocked by this. Could someone explain why this works? A good example of when to use it would also be nice.

This concept is pretty much analogous to C#'s explicit interface implementation. There, too, you can only access the interface's member if you cast the type explicitly to that interface.

I can't comment on why the .NET framework team felt this feature was really necessary though. It might sometimes strengthen encapsulation but I'm not sure of this. In any case, something extremely similar would always be possible using composition instead of (interface) inheritance.

Konrad Rudolph
+2  A: 

Having a private interface implementation basically just allows you to implement an interface without having to muddy your class' API. You can implement IFoo, but only APIs that treat you as an IFoo need to know that.

MSDN says

You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.

bdukes