473,883 Members | 1,683 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What good is Explicit Interface Implementation?

I just read the section (and did the exercise) in the C#
Step by Step book that covers Explict Interface
Implementation (where you specify in the method
implementation the specific interface that you are
implementing in the class.

Other than to resolve the problem that arises when a class
implements two interfaces with the same method signature,
what good is it?

The book says that using EII makes the method effectively
private to the class, but the example cited doesn't agree
with the sample program provided. The example says that a
method, once implemented using the "explicit" syntax must
be called using a cast.

IdentifierToken token = new IdentifierToken ();
token.Accept(vi sitor); // won't complile Accept not
accessible

instead...

((IVisitable)to ken).Accept(vis itor); // major tacky

IdentifierToken implements the IVisitable interface (which
includes Accept() ) using the explicit syntax...

IVisitable.Acce pt(IVisitor visitor) not...
Public Accept(IVisitor visitor)

However the sample program has explicitly implemented
methods, and no cast is used to call them.

So what is EII good for and how does it work?
Nov 15 '05 #1
12 2823
Steve,

Explicit interface implementation is used when you want to implement an
interface but you don't necessarily want to expose those methods on the
interface as part of the class's methods. For example, you might have a
control which needs to filter all windows messages coming into the
application. You would need to implement IMessageFilter for that. With
explicit interface implementation, you can implement the interface, but not
expose the PreProcessMessa ge method publically on your control (as it really
has no use there). This is where explicit interface implementation comes in
handy.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Steve W." <bi********@hot mail.com> wrote in message
news:1e******** *************** *****@phx.gbl.. .
I just read the section (and did the exercise) in the C#
Step by Step book that covers Explict Interface
Implementation (where you specify in the method
implementation the specific interface that you are
implementing in the class.

Other than to resolve the problem that arises when a class
implements two interfaces with the same method signature,
what good is it?

The book says that using EII makes the method effectively
private to the class, but the example cited doesn't agree
with the sample program provided. The example says that a
method, once implemented using the "explicit" syntax must
be called using a cast.

IdentifierToken token = new IdentifierToken ();
token.Accept(vi sitor); // won't complile Accept not
accessible

instead...

((IVisitable)to ken).Accept(vis itor); // major tacky

IdentifierToken implements the IVisitable interface (which
includes Accept() ) using the explicit syntax...

IVisitable.Acce pt(IVisitor visitor) not...
Public Accept(IVisitor visitor)

However the sample program has explicitly implemented
methods, and no cast is used to call them.

So what is EII good for and how does it work?

Nov 15 '05 #2
Nicholas

Good example and thank you
If you look at what Jon Skeet said ( he does not like it )
how can Mr. Skeet do your good example her without EII

Thanks again.
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote
in message news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
Steve,

Explicit interface implementation is used when you want to implement an interface but you don't necessarily want to expose those methods on the
interface as part of the class's methods. For example, you might have a
control which needs to filter all windows messages coming into the
application. You would need to implement IMessageFilter for that. With
explicit interface implementation, you can implement the interface, but not expose the PreProcessMessa ge method publically on your control (as it really has no use there). This is where explicit interface implementation comes in handy.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Steve W." <bi********@hot mail.com> wrote in message
news:1e******** *************** *****@phx.gbl.. .
I just read the section (and did the exercise) in the C#
Step by Step book that covers Explict Interface
Implementation (where you specify in the method
implementation the specific interface that you are
implementing in the class.

Other than to resolve the problem that arises when a class
implements two interfaces with the same method signature,
what good is it?

The book says that using EII makes the method effectively
private to the class, but the example cited doesn't agree
with the sample program provided. The example says that a
method, once implemented using the "explicit" syntax must
be called using a cast.

IdentifierToken token = new IdentifierToken ();
token.Accept(vi sitor); // won't complile Accept not
accessible

instead...

((IVisitable)to ken).Accept(vis itor); // major tacky

IdentifierToken implements the IVisitable interface (which
includes Accept() ) using the explicit syntax...

IVisitable.Acce pt(IVisitor visitor) not...
Public Accept(IVisitor visitor)

However the sample program has explicitly implemented
methods, and no cast is used to call them.

So what is EII good for and how does it work?


Nov 15 '05 #3
100
As an example of when using EII comes handy could be when you want to
implemet typed list class which support IList interface

class MyClass
{
}

class MyList : IList
{
}

You can do that like:

class MyList : IList
{
public int Add(MyClass obj)
{
//save the reference in a list and return the index
}

int IList.Add(objec t obj)
{
//this will throw execption if the class is added using IList and
the obj is not of MyClass type.
//You can make your own typecheck and throw your own exception
return this.Add((MyCla ss)obj);
}
}

if you don't do EII the class will expose method
int Add(object obj) which doesn't make sence in typed list class.
MyList has to accept only objects of MyClass

HTH
B\rgds
100

"Steve W." <bi********@hot mail.com> wrote in message
news:1e******** *************** *****@phx.gbl.. .
I just read the section (and did the exercise) in the C#
Step by Step book that covers Explict Interface
Implementation (where you specify in the method
implementation the specific interface that you are
implementing in the class.

Other than to resolve the problem that arises when a class
implements two interfaces with the same method signature,
what good is it?

The book says that using EII makes the method effectively
private to the class, but the example cited doesn't agree
with the sample program provided. The example says that a
method, once implemented using the "explicit" syntax must
be called using a cast.

IdentifierToken token = new IdentifierToken ();
token.Accept(vi sitor); // won't complile Accept not
accessible

instead...

((IVisitable)to ken).Accept(vis itor); // major tacky

IdentifierToken implements the IVisitable interface (which
includes Accept() ) using the explicit syntax...

IVisitable.Acce pt(IVisitor visitor) not...
Public Accept(IVisitor visitor)

However the sample program has explicitly implemented
methods, and no cast is used to call them.

So what is EII good for and how does it work?

Nov 15 '05 #4
I use it every once in a while. In fact, I used it yesterday, because I had
to. The project I'm working on uses Interfaces extensively. We have a lot
of objects that must implement the same set of methods and set apart in
multiple projects. Interfaces help us make all the objects behave themselves
and allow us to avoid circularities caused by cross project composition.

Anyway, yesterday morning I did a Get Latest and found that someone on the
team added a Name property with only a get accessor to Interface IFoo. I
already had a Name property in my type with both get and set accessors, so
the compile died because I was setting my name property, which would not
have otherwise have been detected, potentially causing runtime problems
later. Anyway, the fix was to implement the IFoo.Name property with the get
and no set accessor. Since we assign instantiated objects to variables of
the interface type (rather than casting), the proper method gets called,
preserving the semantic integrity of the operation.

Joe
--
http://www.csharp-station.com

"Steve W." <bi********@hot mail.com> wrote in message
news:1e******** *************** *****@phx.gbl.. .

Other than to resolve the problem that arises when a class
implements two interfaces with the same method signature,
what good is it?

Nov 15 '05 #5
Joe,
Can you please provide us with a small sample of code to illustrate your fix
Please provide before and after code
Thank you for your input
"Joe Mayo" <jm***@ddiieess ppaammeerrssddi iee.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
I use it every once in a while. In fact, I used it yesterday, because I had to. The project I'm working on uses Interfaces extensively. We have a lot
of objects that must implement the same set of methods and set apart in
multiple projects. Interfaces help us make all the objects behave themselves and allow us to avoid circularities caused by cross project composition.

Anyway, yesterday morning I did a Get Latest and found that someone on the
team added a Name property with only a get accessor to Interface IFoo. I
already had a Name property in my type with both get and set accessors, so
the compile died because I was setting my name property, which would not
have otherwise have been detected, potentially causing runtime problems
later. Anyway, the fix was to implement the IFoo.Name property with the get and no set accessor. Since we assign instantiated objects to variables of
the interface type (rather than casting), the proper method gets called,
preserving the semantic integrity of the operation.

Joe
--
http://www.csharp-station.com

"Steve W." <bi********@hot mail.com> wrote in message
news:1e******** *************** *****@phx.gbl.. .

Other than to resolve the problem that arises when a class
implements two interfaces with the same method signature,
what good is it?


Nov 15 '05 #6
100
Hi Jon,
100 <10*@100.com> wrote:

<snip>
if you don't do EII the class will expose method
int Add(object obj) which doesn't make sence in typed list class.
MyList has to accept only objects of MyClass


It still exposes int Add(object obj) - it just hides it very slightly
so that only code looking at it in a certain kind of way can see it.


Sometimes I have to implement a standard interface just because the
framework needs it.
As in my example I have designed the list to hold *only* MyClass objects. I
have to pass the objects to some library class method, which expects IList,
though. Hiding interface implementation tells the users of my class that
they shouldn't use IList members in normal circumstances. They still can,
though.
Another example is *Control.Contro lCollection*. The designer of this class
decided to implement IList (maybe there is some reason to do so) , but
doesn't want to implement IList.Insert method. S/he hid all or part of
IList's methods and added new method *SetChildIndex* . Anyway because the
objects can be cast to IList IList.Insert throws an excpetion. How ever when
I needed to insert a control at index 0 I saw that there is no such a method
exposed by the class. However, I tried to cast the collection to IList, but
I already new that it won't do.

Anyway, I believe that the main reason for EII is to make posible to
implement different interfaces, which have methods with the same prototype.
All other usages is just tricks that *might* make the code more clear.
Nov 15 '05 #7
I can't post client code, but here's the scenario.

*** Initial Code

using System;

interface IMyInterface
{
}

class MyBase
{
private string m_name;

public string Name
{
get { return m_name; }
set { m_name = value; }
}
}

class MyClass : MyBase, IMyInterface
{
static void Main()
{
MyClass myCl = new MyClass();
myCl.Run();

Console.WriteLi ne("myClass.Nam e: {0}", myCl.Name);
Console.ReadLin e();
}

public void Run()
{
this.Name = "Joe";
}
}

Notice that I have a property that is being set on an instance of this
MyClass. For other purposes, MyClass implements IMyInterface.

Now, someone decides to change IMyInterface like this:

*** Intermediate Code

interface IMyInterface
{
string Name
{
get;
}
// plus some other new stuff.
}

class MyClass : MyBase, IMyInterface
{
// other implementation elided for clarity

public void Run()
{
this.Name = "Joe"; // compiler error
}
public string Name
{
get { return "Mayo, Joe"; }
}

Although MyClass implements Name by virtue of inheriting it from MyBase,
IMyInterface specifies other new members that I must include. So, I do a
thorough review of MyClass and make sure that it implements IMyInterface
properly (in VS.NET retype the interface name and press the Tab key),
including the IMyInterface version of Name. This generates a compiler error
on MyClass.Name because it is hiding MyBase.Name and only implements a get.

So, I do an explicit implementation of Name in MyClass that allows me to use
MyClass.Name and IMyInterface name in the proper contexts and preserve the
semantics of my type.

*** Final Code

using System;

interface IMyInterface
{
string Name
{
get;
}
}

class MyBase
{
private string m_name;

public string Name
{
get { return m_name; }
set { m_name = value; }
}
}

class MyClass : MyBase, IMyInterface
{
static void Main()
{
MyClass myCl = new MyClass();
myCl.Run();

IMyInterface myIf = new MyClass();

Console.WriteLi ne("myCl.Name: {0}", myCl.Name);
Console.WriteLi ne("myIf.Name: {0}", myIf.Name);
Console.ReadLin e();
}

public void Run()
{
this.Name = "Joe";
}

string IMyInterface.Na me
{
get { return "Mayo, Joe"; }
}
}

And here's the output:

myCl.Name: Joe
myIf.Name: Mayo, Joe

Joe
--
http://www.csharp-station.com

"News VS.NET ( MS ILM )" <sq**********@h otmail.com> wrote in message
news:Ok******** *****@TK2MSFTNG P11.phx.gbl...
Joe,
Can you please provide us with a small sample of code to illustrate your fix Please provide before and after code
Thank you for your input
"Joe Mayo" <jm***@ddiieess ppaammeerrssddi iee.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
I use it every once in a while. In fact, I used it yesterday, because I

had
to. The project I'm working on uses Interfaces extensively. We have a lot of objects that must implement the same set of methods and set apart in
multiple projects. Interfaces help us make all the objects behave

themselves
and allow us to avoid circularities caused by cross project composition.

Anyway, yesterday morning I did a Get Latest and found that someone on the team added a Name property with only a get accessor to Interface IFoo. I
already had a Name property in my type with both get and set accessors, so the compile died because I was setting my name property, which would not
have otherwise have been detected, potentially causing runtime problems
later. Anyway, the fix was to implement the IFoo.Name property with the

get
and no set accessor. Since we assign instantiated objects to variables of the interface type (rather than casting), the proper method gets called,
preserving the semantic integrity of the operation.

Joe
--
http://www.csharp-station.com

"Steve W." <bi********@hot mail.com> wrote in message
news:1e******** *************** *****@phx.gbl.. .

Other than to resolve the problem that arises when a class
implements two interfaces with the same method signature,
what good is it?



Nov 15 '05 #8
Jon,

I tend to agree with you for many interfaces. But if the interface is for
something that isn't really the main purpose of the class, you often don't
want to make it visible to the user.

The Serialize function on ISerializable is a good example. I don't want it
cluttering up the user model.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@news.microsof t.com...
"News VS.NET \( MS ILM \)" <sq**********@h otmail.com> wrote:
Good example and thank you
If you look at what Jon Skeet said ( he does not like it )
how can Mr. Skeet do your good example her without EII


I wouldn't. I believe if you're going to implement an interface, you
just implement it - none of this "Well, I sort of implement it, but
only if you cast to the right thing."

It doesn't actually stop anyone from doing things, it just makes it
harder to do them due to casting which looks strange.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

Nov 15 '05 #9
Thank you, I don't expect you to post client code, just an example
"Joe Mayo" <jm***@ddiieess ppaammeerrssddi iee.com> wrote in message
news:eD******** *****@TK2MSFTNG P10.phx.gbl...
I can't post client code, but here's the scenario.

*** Initial Code

using System;

interface IMyInterface
{
}

class MyBase
{
private string m_name;

public string Name
{
get { return m_name; }
set { m_name = value; }
}
}

class MyClass : MyBase, IMyInterface
{
static void Main()
{
MyClass myCl = new MyClass();
myCl.Run();

Console.WriteLi ne("myClass.Nam e: {0}", myCl.Name);
Console.ReadLin e();
}

public void Run()
{
this.Name = "Joe";
}
}

Notice that I have a property that is being set on an instance of this
MyClass. For other purposes, MyClass implements IMyInterface.

Now, someone decides to change IMyInterface like this:

*** Intermediate Code

interface IMyInterface
{
string Name
{
get;
}
// plus some other new stuff.
}

class MyClass : MyBase, IMyInterface
{
// other implementation elided for clarity

public void Run()
{
this.Name = "Joe"; // compiler error
}
public string Name
{
get { return "Mayo, Joe"; }
}

Although MyClass implements Name by virtue of inheriting it from MyBase,
IMyInterface specifies other new members that I must include. So, I do a
thorough review of MyClass and make sure that it implements IMyInterface
properly (in VS.NET retype the interface name and press the Tab key),
including the IMyInterface version of Name. This generates a compiler error on MyClass.Name because it is hiding MyBase.Name and only implements a get.
So, I do an explicit implementation of Name in MyClass that allows me to use MyClass.Name and IMyInterface name in the proper contexts and preserve the
semantics of my type.

*** Final Code

using System;

interface IMyInterface
{
string Name
{
get;
}
}

class MyBase
{
private string m_name;

public string Name
{
get { return m_name; }
set { m_name = value; }
}
}

class MyClass : MyBase, IMyInterface
{
static void Main()
{
MyClass myCl = new MyClass();
myCl.Run();

IMyInterface myIf = new MyClass();

Console.WriteLi ne("myCl.Name: {0}", myCl.Name);
Console.WriteLi ne("myIf.Name: {0}", myIf.Name);
Console.ReadLin e();
}

public void Run()
{
this.Name = "Joe";
}

string IMyInterface.Na me
{
get { return "Mayo, Joe"; }
}
}

And here's the output:

myCl.Name: Joe
myIf.Name: Mayo, Joe

Joe
--
http://www.csharp-station.com

"News VS.NET ( MS ILM )" <sq**********@h otmail.com> wrote in message
news:Ok******** *****@TK2MSFTNG P11.phx.gbl...
Joe,
Can you please provide us with a small sample of code to illustrate your fix
Please provide before and after code
Thank you for your input
"Joe Mayo" <jm***@ddiieess ppaammeerrssddi iee.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
I use it every once in a while. In fact, I used it yesterday, because I
had
to. The project I'm working on uses Interfaces extensively. We have a lot of objects that must implement the same set of methods and set apart
in multiple projects. Interfaces help us make all the objects behave

themselves
and allow us to avoid circularities caused by cross project composition.
Anyway, yesterday morning I did a Get Latest and found that someone on the team added a Name property with only a get accessor to Interface IFoo. I already had a Name property in my type with both get and set accessors, so
the compile died because I was setting my name property, which would
not have otherwise have been detected, potentially causing runtime problems later. Anyway, the fix was to implement the IFoo.Name property with the get
and no set accessor. Since we assign instantiated objects to variables

of the interface type (rather than casting), the proper method gets

called, preserving the semantic integrity of the operation.

Joe
--
http://www.csharp-station.com

"Steve W." <bi********@hot mail.com> wrote in message
news:1e******** *************** *****@phx.gbl.. .
>
> Other than to resolve the problem that arises when a class
> implements two interfaces with the same method signature,
> what good is it?



Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

92
6579
by: Reed L. O'Brien | last post by:
I see rotor was removed for 2.4 and the docs say use an AES module provided separately... Is there a standard module that works alike or an AES module that works alike but with better encryption? cheers, reed
12
3312
by: Steven T. Hatton | last post by:
This is something I've been looking at because it is central to a currently broken part of the KDevelop new application wizard. I'm not complaining about it being broken, It's a CVS images. Such things happen. The whole subsystem is going through radical changes. I don't really want to say what I think of the code just yet. That would influence the opinions of others, and I really want to know how other people view these things,...
21
13858
by: Helge Jensen | last post by:
I've got some data that has Set structure, that is membership, insert and delete is fast (O(1), hashing). I can't find a System.Collections interface that matches the operations naturally offered by Sets. - ICollection cannot decide containment - IList promises indexability by the natural numbers, which is not achievable (since i hash elements, not sort them). - IDictionary is definatly not setlike. Although I can, of course, define...
13
4281
by: Stephen Walch | last post by:
Error C2392 is hitting me hard! I have a managed C++ library that implements a bunch of fixed interfaces. For example, one interface is: public abstract interface IDbCommand { public abstract new System.Data.IDbConnection Connection }
10
1728
by: Martin Zenkel | last post by:
Assumed two assemblies (one C# and one C++), C++ refers to C#. The follwing code compiles and works well under VS 2002! VS 2003 C++ compiler reports the error "error 2555: 'TestNamespace::ClassB::IInterfaceB.get_Content': overriding virtual function return type differs and is not covariant from 'TestNamespace::ClassA::get_Content'" Explicit implementation of "IInterfaceA.Content" in
0
2226
by: Ken | last post by:
Hi I have a little application that does datavalidation. It supports dynamically loaded plugins (you drop a dll with a class implementing IValidator<Tin the same dir as the main application). All classes that implement this interface are shown in a drop down in a DataGridViewComboBoxColumn named Validator. By choosing the class to validate this specific data in the drop downbox IValidator<T>.Validate is called and returns true/false....
1
2765
by: recherche | last post by:
Hola! I tried the following public implementation of interface indexer by struct (Code Snippet 1) in private and explicit implementation by struct (Code Snippet 2) but in vain. Please help! Code Snippet 1:
1
3228
by: =?Utf-8?B?Sk0=?= | last post by:
In an application I have an interface with methods and properties. The interface is used on a Class (ie class MyClass : IMyClassA, IMyClassB). On a windows form I define a BindingSource (_bindingMyClass) where I set the DataSource property to the interface IMyClass. Now when the MyClass object is instantiated I set the BindingSource to the instance of the IMyClass interface (_MyClass) _bindingMyClass.DataSource = this._MyClass;
2
1915
by: puzzlecracker | last post by:
I don't see the purpose of explicit interface implementation other than to hide its signature in the class that implements it, and, instead, write your own, perhaps with a different signature, implementation. Also, if you implement more than two interfaces with the same method, which is rarity in practice or so it seems. To me it appears a shallow end... Am I missing something? Thanks
0
9938
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9791
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11140
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10742
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7125
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5797
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5991
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4611
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3232
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.