P
Peter Duniho
coder316 said:In the following code I am declaring and useing an interface.Its
pretty strait forward.
Except that it's not. Yes, you are declaring and implementing an
interface. But you're not _using_ it at all.
A better code example would look like this:
namespace Interface2
{
interface MyInterface
{
int AddNumbers(int x, int y);
}
class Program
{
static void Main(string[] args)
{
MyInterface myinterface = new UseInterface();
Console.WriteLine(myinterface.AddNumbers(2,2));
Console.ReadLine();
}
}
class UseInterface : MyInterface
{
private int MyInterface.AddNumbers(int a, int b)
{
int c;
return c = a + b;
}
}
}
I've made a couple of changes, one very important, one not so important:
-- very important: the variable type is now "MyInterface" rather
than "UseInterface". Typed as the actual object type, you'll have
access to all public members of the type, regardless of interface
implementations. So your previous example wasn't very interesting, as
the interface itself could have been omitted altogether without changing
the behavior of the code (or even whether it would compile!). With the
variable types as "MyInterface", you can add all sorts of other stuff to
"UseInterface", but none of that will show up in the variable
"MyInterface"...you'll still only be able to call the AddNumbers() method.
-- less important: I made the interface implementation "explicit".
That is, the method name is qualified with the interface name. This
means that the _only_ way to call the method is via the interface. You
can't call it with a variable of type "UseInterface"; the expression for
the reference _has_ to be "MyInterface".
The important thing to keep in mind is that when a class implements an
interface, other code can access all the members of the class _that are
included as implementation of that interface_ using only the interface
type itself, without knowing anything else about the class.
That's what happens with the Sort() method. It doesn't need to know
anything about the elements of the array, except that they implement the
IComparable interface. Knowing that, Sort() can simply cast each object
to IComparable, and then call the CompareTo() method declared in the
IComparable interface.
Pete