Interfaces

  • Thread starter Duncan McNutt .[FTSE]
  • Start date
D

Duncan McNutt .[FTSE]

Why does code derive from for example, IComparer

ie,

class SomeClass : IComparer
{
public SomeClass()
{
}

public int Compare(object x, object y)
{
return someInt;
}
}


When it just uses that and could have done without deriving ICompare and
got the same result.

class SomeClass
{
public SomeClass()
{
}

public int Compare(object x, object y)
{
return someInt;
}
}
 
D

Duncan McNutt .[FTSE]

And another question...

Because SomeClass derives from the IComparer interface


if i use SomeClass as a base of another like...

class SomeNewClass : SomeClass
{
public SomeNewClass()
{
}
}

Would that above fail due to no Compare method as SomeClass is derived from
ICompare and it MUST implement Compare.. like..

class SomeNewClass : SomeClass
{
public SomeNewClass()
{
}

public int Compare(object x, object y)
{
return someInt;
}
}

The above would work.

Do i understand this correctly?
 
I

Ignacio Machin

Hi Duncan,

You do not derive from an interface, you implement it, there is a diference,
an interface is like a template, it has no implementation it only assure
that the classes that implement it have a predefined setof methods ( the
interface ) , when you derive from a class you extend that class, add new
functionality. you do not do that with an interface.

Hope this help,
 
D

Duncan McNutt .[FTSE]

oh well yeah oops :D wasnt thinking *gets coffee*

So why inherit from ICompare when its just as easy to implement Compare
anyway and its derived.
 
I

Ignacio Machin

Hi Duncan,


I would suggest you something, if you have this kind of doubt, try it !! ,
do not missunderstand me, I believe that the best way to learn is
experimenting, your code will not fail cause as I explained in the previous
post when you derive you are extending therefore the new class gets all the
parent's functionality.

Hope this help,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation


Duncan McNutt . said:
And another question...

Because SomeClass derives from the IComparer interface


if i use SomeClass as a base of another like...

class SomeNewClass : SomeClass
{
public SomeNewClass()
{
}
}

Would that above fail due to no Compare method as SomeClass is derived from
ICompare and it MUST implement Compare.. like..

class SomeNewClass : SomeClass
{
public SomeNewClass()
{
}

public int Compare(object x, object y)
{
return someInt;
}
}

The above would work.

Do i understand this correctly?

--

Duncan McNutt
Microsoft Product Deactivation Team
 
P

Peter Vidler

Hi,
So why inherit from ICompare when its just as easy to implement
Compare anyway and its derived.

Because then you can use an object of that type wherever IComparer is asked
for (i.e. calls to methods, etc). Otherwise there is no way to tell if an
object supports the Compare method without having a reference to the exact
type of the object.

Pete
 
F

Frank Drebin

The key element is that the purpose of an interface is that you can write
your code to a generic "interface"..

For example, say you have a Windows app that needs to connect to a
datasource. That datasource could be a real database, a remote web service
and also an offline file. But you want to abstract HOW the datasource gets
it's data. If you couldn't abstract it, you'd have to write 3 versions of
code mixed in with your main application - to do this.

but instead, you could write your application to use the IDataAccess
interface (this is an interface you write, it has Connect() Authenticate(),
etc)..

Then you have classes such as Database, WebService and OfflineAccess that
implement that interface.

So Interfaces aren't so much a small-scale time-saver, they make more and
more sense the larger the app gets - and the purpose is to abstract the
specific of how something gets done.

Using your examples, if you write your application to use the IComparer
interface:

IComparer objMyComparer = new SomeClass();

Since SomeClass implements IComparer - the above is valid. Imagine that you
could have several different KINDS of comparers - and you would only need to
write your new classes to implement that same IComparer interface.

hope that helps..
 
D

Duncan McNutt .[FTSE]

Yeah I understand an Interface is a contract, that must be implemented but I
see code that has implemented that interface but why would it need to when
it can just as easily implement it anyway and not have tim use ICompare in
the class definition.

Whats to stop me just coding a public int Compare(object x, object y) method
anyway without referring to IComapre?



--

Duncan McNutt
Microsoft Product Deactivation Team
--


Ignacio Machin said:
Hi Duncan,

You do not derive from an interface, you implement it, there is a diference,
an interface is like a template, it has no implementation it only assure
that the classes that implement it have a predefined setof methods ( the
interface ) , when you derive from a class you extend that class, add new
functionality. you do not do that with an interface.

Hope this help,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
 
P

Peter Vidler

Hi,
Whats to stop me just coding a public int Compare(object x, object y)

Because my CompareStuff method ("public int CompareStuff(IComparer[]
stuff)") couldn't use your class unless you implement IComparer.

Hope that syntax was correct :)

Pete
 
D

Duncan McNutt .[FTSE]

Yeah but why must that class implement ICompare when it can just as easily
make a public Compare (obj , obj) method and be the same.



--

Duncan McNutt
Microsoft Product Deactivation Team
--


Ignacio Machin said:
Hi Duncan,

You do not derive from an interface, you implement it, there is a diference,
an interface is like a template, it has no implementation it only assure
that the classes that implement it have a predefined setof methods ( the
interface ) , when you derive from a class you extend that class, add new
functionality. you do not do that with an interface.

Hope this help,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
 
D

Duncan McNutt .[FTSE]

yeah I know, i just wasnt thinking, caffine levels droped :D

But my question is, why implement ICompare when I can just as easily make
the method without reference to IComapre at all in the class.

What is the benifit.


--

Duncan McNutt
Microsoft Product Deactivation Team
--


Ignacio Machin said:
Hi Duncan,


I would suggest you something, if you have this kind of doubt, try it !! ,
do not missunderstand me, I believe that the best way to learn is
experimenting, your code will not fail cause as I explained in the previous
post when you derive you are extending therefore the new class gets all the
parent's functionality.

Hope this help,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation


Duncan McNutt . said:
And another question...

Because SomeClass derives from the IComparer interface


if i use SomeClass as a base of another like...

class SomeNewClass : SomeClass
{
public SomeNewClass()
{
}
}

Would that above fail due to no Compare method as SomeClass is derived from
ICompare and it MUST implement Compare.. like..

class SomeNewClass : SomeClass
{
public SomeNewClass()
{
}

public int Compare(object x, object y)
{
return someInt;
}
}

The above would work.

Do i understand this correctly?

--

Duncan McNutt
Microsoft Product Deactivation Team
--


Duncan McNutt . said:
Why does code derive from for example, IComparer

ie,

class SomeClass : IComparer
{
public SomeClass()
{
}

public int Compare(object x, object y)
{
return someInt;
}
}


When it just uses that and could have done without deriving
ICompare
and
 
D

Duncan McNutt .[FTSE]

ahh ok, thanks that clears it up.

I just saw it in a small snipit of code on a little project and It just
didnt make sense why he used it for that example but yeah i can see the
benifit of that when scaling it up :D

So, would it be good practice to implement such interfaces where possible,
regardless of size, just for future or where basically I can see a specific
need for generic implementation?

--

Duncan McNutt
Microsoft Product Deactivation Team
--


Frank Drebin said:
The key element is that the purpose of an interface is that you can write
your code to a generic "interface"..

For example, say you have a Windows app that needs to connect to a
datasource. That datasource could be a real database, a remote web service
and also an offline file. But you want to abstract HOW the datasource gets
it's data. If you couldn't abstract it, you'd have to write 3 versions of
code mixed in with your main application - to do this.

but instead, you could write your application to use the IDataAccess
interface (this is an interface you write, it has Connect() Authenticate(),
etc)..

Then you have classes such as Database, WebService and OfflineAccess that
implement that interface.

So Interfaces aren't so much a small-scale time-saver, they make more and
more sense the larger the app gets - and the purpose is to abstract the
specific of how something gets done.

Using your examples, if you write your application to use the IComparer
interface:

IComparer objMyComparer = new SomeClass();

Since SomeClass implements IComparer - the above is valid. Imagine that you
could have several different KINDS of comparers - and you would only need to
write your new classes to implement that same IComparer interface.

hope that helps..
 
F

Frank Drebin

Since I've started developing in OO - I've been learning that the more you
can abstract, the better...

So it really is just a trade-off of - how much time (now, and in the future)
will writing an interface save me.. versus how long will it take me to
write.

But as a general rule, I'm a big fan abstracting as much as possible,
whenever possible...

Duncan McNutt . said:
ahh ok, thanks that clears it up.

I just saw it in a small snipit of code on a little project and It just
didnt make sense why he used it for that example but yeah i can see the
benifit of that when scaling it up :D

So, would it be good practice to implement such interfaces where possible,
regardless of size, just for future or where basically I can see a specific
need for generic implementation?

--

Duncan McNutt
Microsoft Product Deactivation Team
--


Frank Drebin said:
The key element is that the purpose of an interface is that you can write
your code to a generic "interface"..

For example, say you have a Windows app that needs to connect to a
datasource. That datasource could be a real database, a remote web service
and also an offline file. But you want to abstract HOW the datasource gets
it's data. If you couldn't abstract it, you'd have to write 3 versions of
code mixed in with your main application - to do this.

but instead, you could write your application to use the IDataAccess
interface (this is an interface you write, it has Connect() Authenticate(),
etc)..

Then you have classes such as Database, WebService and OfflineAccess that
implement that interface.

So Interfaces aren't so much a small-scale time-saver, they make more and
more sense the larger the app gets - and the purpose is to abstract the
specific of how something gets done.

Using your examples, if you write your application to use the IComparer
interface:

IComparer objMyComparer = new SomeClass();

Since SomeClass implements IComparer - the above is valid. Imagine that you
could have several different KINDS of comparers - and you would only
need
to
write your new classes to implement that same IComparer interface.

hope that helps..

Duncan McNutt . said:
Why does code derive from for example, IComparer

ie,

class SomeClass : IComparer
{
public SomeClass()
{
}

public int Compare(object x, object y)
{
return someInt;
}
}


When it just uses that and could have done without deriving
ICompare
and
 
J

Jon Skeet

Duncan McNutt . said:
Why does code derive from for example, IComparer

ie,

class SomeClass : IComparer
{
public SomeClass()
{
}

public int Compare(object x, object y)
{
return someInt;
}
}


When it just uses that and could have done without deriving ICompare and
got the same result.

No you didn't. You can't use an instance of SomeClass to provide the
comparisons for Array.Sort, for instance, unless is implements
IComparer.
 
D

Duncan McNutt .[FTSE]

I just got confused because a small code project i saw as an example used
it in the class but never elsewhere, just seemed pointless for that example.

--

Duncan McNutt
Microsoft Product Deactivation Team
 
P

Peter Vidler

Hi,
And I can use multiple interfaces on a class? i.,e


class SomeClass : ICompare , ISomethingOrOther

Yes that's fine.

and then implement both or just one?

No you must implement all members of both. Although you can use explicit
implementation:

class SomeClass : IComparer
{
public int IComparer.Compare( object x, object y )
{
// ...
}
}

This will mean that the Compare method is no longer available from the
SomeClass reference, but can be used when you cast to an IComparer
reference:

SomeClass c = new SomeClass();
c.Compare(...); // error
ICompare comp = c as ICompare;
comp.Compare(...); // fine
( ( ICompare )c ).Compare(...); // fine

This is useful when you don't want to clutter up the class with too many
public methods (*cough* Java *cough* ;) ), but you still want the
interface's functionality. It is required to do it this way if two or more
interfaces have members with the same signature (name and parameters).
can I also extend that by having methods that arnt in that
interface yet still pass it into those CompareStuff (IComparer[]..
blah

You can still add your own methods, and still use a function that takes an
IComparer. The reference to IComparer (which you will be passing to the
CompareStuff method) will only have access to the IComparer functionality,
however.
even tho it has the interface, and more methods not specified by
that interface, if so, what happens if 2 interfaces have similar
methods?

See above. If there's ever any confusion over a c# feature I always look at
this webpage first:

http://www.jaggersoft.com/pubs/AProgrammersOverviewOfCSharp.htm

Pete
 
P

Peter Vidler

Not sure if this came through okay, so here it is again with some added
detail:

Hi,
And I can use multiple interfaces on a class? i.,e


class SomeClass : ICompare , ISomethingOrOther

Yes that's fine.

and then implement both or just one?

No you must implement all members of both. Although you can use explicit
implementation:

class SomeClass : IComparer
{
// non-public explicit implementation
int IComparer.Compare( object x, object y )
{
// ...
}
}

This will mean that the Compare method is no longer available from the
SomeClass reference, but can be used when you cast to an IComparer
reference:

SomeClass c = new SomeClass();
c.Compare(...); // error
IComparer comp = c as IComparer;
comp.Compare(...); // fine
( ( IComparer )c ).Compare(...); // fine

This is useful when you don't want to clutter up the class with too many
public methods (*cough* Java *cough* ;) ), but you still want the
interface's functionality. It is required to do it this way if two or more
interfaces have members with the same signature (name and parameters).

There's also language support for interfaces. If you implement the
IDisposable interface you can use a "using" statement. This is because this:

using( SomeClass c = new SomeClass() )
{
// do stuff
}

Compiles to the equivalent of this:

SomeClass c = new SomeClass();
try
{
// do stuff
}
finally
{
if ( c != null )
{
( ( IDisposable )c ).Dispose();
}
}

There is also language support for IEnumerable which allows your classes to
be used in a foreach statement.
can I also extend that by having methods that arnt in that
interface yet still pass it into those CompareStuff (IComparer[]..
blah

You can still add your own methods, and still use a function that takes an
IComparer. The reference to IComparer (which you will be passing to the
CompareStuff method) will only have access to the IComparer functionality,
however.
even tho it has the interface, and more methods not specified by
that interface, if so, what happens if 2 interfaces have similar
methods?

See above. If there's ever any confusion over a c# feature I always look at
this webpage first:

http://www.jaggersoft.com/pubs/AProgrammersOverviewOfCSharp.htm

Pete
 
F

Frank Drebin

That is the slick part about interfaces. You can define a variable of type
"some interface" - and then instantiate it with ANY class that implements
that interface. With the example I gave before.. Imagine you have an
IDataAccess interface that defines ways that you can get data - and includes
login and logout. Now imagine I have 3 classes "WebSvcAccess", "SQLServer"
and "OfflineAccess" that all implement that interface.

Let me stress the signifigance of this.

The ENTIRE application is written to the IDataAccess interface, it has NO
IDEA what those other classes are - and at RUN-time, the user chooses thier
access type. So long as those classes have correctly implemented the
interface - the whole app runs the same no matter what the connection type.

So one time, I do this:

IDataAccess objMainAccessObject = new WebSvcsAccess();
-or-
IDataAccess objMainAccessObject = new SQLServer();
-or-
IDataAccess objMainAccessObject = new OfflineAccess();

And it is ONLY at that time that my application knows what kind of access
they will be using. After that, the method of data access is *completely*
abstracted. This is basically the "factory" design pattern (more or less).
The whole rest of the app just interacts with objMainAccessObject as if it
was the same all along. And in theory, you could even switch access types -
like if you went from offline access to being plugged into the net. you
could freeze the app, re-instantiate objMainAccessObject with new
SQLServer() and pick up where you left off. It's really a hugely powerful
concept.

So you aren't creating an instance of an interface (because you can't) - but
you can define a variable to be of an interfaces "type", and then
instantiate it with an object that implements that interface.. this alone is
such a GREAT feature of OO that you just couldn't do in VB6.. or that you
could do in C++, but you could also easily work around this. It seems much
easier to enforce this in a real strongly-typed environment like this...



Stan said:
Nice to see this thread appear as I have my own interface based query to put
to the group. I was just reading up on an article that has some sample code
and was perplexed to see this line appear,

ICodeCompiler loCompiler = new CSharpCodeProvider().CreateCompiler();

I believe this is similar to a sample that someone else has posted to this
thread. What confuses me is the fact that you are able to create an instance
of type interface. I would have thought that you would have to create a type
of something which implements the interface, since the interface defines
only exposed methods i.e. no implementation and doesn't even define
constructors. What is the base type of the instance in this case? Is it
simply an System.object type which is obliged to support the interface? I'm
thinking that must be it. I think this is different to specifying an
interface as a function argument, in which case we are saying that whatever
is passed must support the interface.
 
J

Jon Skeet

Stan said:
Nice to see this thread appear as I have my own interface based query to put
to the group. I was just reading up on an article that has some sample code
and was perplexed to see this line appear,

ICodeCompiler loCompiler = new CSharpCodeProvider().CreateCompiler();

I believe this is similar to a sample that someone else has posted to this
thread. What confuses me is the fact that you are able to create an instance
of type interface.

You're not - just as the line:

object x = new StringBuilder();

is creating an instance of StringBuilder, not of Object - it's just
that you can assign a reference of type StringBuilder to a variable of
type Object. It's exactly the same deal with interfaces - you can
assign a reference of any type which implements the interface to a
variable whose type is the interface.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top