Specify member scope in Interface Classes

  • Thread starter Thread starter aaronh64
  • Start date Start date
A

aaronh64

Have you ever noticed that when you look at an Interface Class
definition (ie IDisposable), the methods or properties belonging to the
class are defined as abstract (C#) or overridable (vb)?


How can this be? When I create an Interface class and try to give
methods any signature at all, I receive compile errors. In terms of
scope, all that I can define for method implementation is the return
type, method name, and arguments. I cannot define a method as
public/private, abstract/virtual (C#), overridable (VB), etc.
How did Microsoft accomplish this? You'll notice that pretty much all
Interface classes in the .NET framework have this kind of scope.


Why do I care you might ask? I would like to create an Interface class
and have classes that implement it hide the methods, so that the
interface method(s) implementation is private. A good example of how
the framework is doing this is in the
System.Web.UI.WebControls.WebControl class.


Notice that the class implements the IAttributeAccessor interface,
which defines 2 methods (SetAttribute and GetAttribute). Also notice
that these methods are NOT accessible from WebControl or any inheriting
control, such as TextBox, Button, etc. How did they accomplish this
behavior? As of now, I'm thinking that the 2 methods are marked with
an attribute, but which one?


Any thoughts or ideas as to how they accomplished this would be great!
Aaron Hanusa
 
Hello (e-mail address removed),

They are not privately implemented, rather explicitly implemented. Simply
put, the implementation is still public, however, it is available only through
the interface, rather than on the class directly.

The implementation in all likelihood looks something like this:

class WebControl : IAttributeAccessor
{
string IAttributeAccessor.GetAttribute(string key)
{
// some code
}

void IAttributeAccessor.SetAttribute(string key, string value)
{
// some code
}
}

So, the way that this can get called is as such (assuming the class above):

WebControl ctl = new WebControl();
IAttributeAccessor accessor = ctl as IAttributeAccessor;
if (accessor != null)
{
accessor.SetAttribute(key, value);
}

You can read more about explicit interface implementation at: http://msdn.microsoft.com/library/d...lkexplicitinterfaceimplementationtutorial.asp

Hope this helps... If not, please follow up...
 
Back
Top