Interfaces (NOOBIE)

  • Thread starter Thread starter ME
  • Start date Start date
M

ME

I am learning C#. I can't seem to understand why one would use an
interface, it doesn't seem to do anything at all. Why not just leave the
interface out and just code the properties and what not with out them? I
have found numerous articles on the subject but I can't seem to find one
that gives me a programming example of WHY. Plenty out there of how. Just
need to know WHY. Please try to keep it simple I am kind of slow when it
comes to this stuff.

Kind Regards,

Matt
 
Say you have a class called circle and a class called rectangle.
They are completely different, one has corners, the other is smooth, and
so on.
Yet, you have a method that takes either a circle or an rectangle and uses
their Volume or Surface property.
If you make an IGeometricObject interface (always use I to indicate
interface) you can pass any class "subscribing" to IGeometricObject and
not worry about wether the object is rectangle or circle.

interface IGeometricObject
{
public float GetVolume(); // a method all subscribers will have to
implement
public float GetSurface(); // anther such method
}

class Rectangle : IGeometricObject
{

public float GetVolume()
{
// TODO: Add Rectangle.GetVolume implementation
return 0;
}

public float GetSurface()
{
// TODO: Add Rectangle.GetSurface implementation
return 0;
}
}


class Circle : IGeometricObject
{

public float GetVolume()
{
// TODO: Add Circle.GetVolume implementation
return 0;
}

public float GetSurface()
{
// TODO: Add Circle.GetSurface implementation
return 0;
}
}

class SomeClass
{
public SomeClass()
{
Circle aCircle = new Circle();
Rectangle aRectangel = new Rectangle();

float number = calculateStuff(aCircle) + calculateStuff(aRectangle);
}

private float calculateStuff(IGeometricObject geo)
{
return geo.GetVolume() * geo.GetSurface();
}
}

So, if you have two different classes, but they both share some common
stuff, or you want them to share something (like being sortable in an
ArrayList, just "subscribe" to IComparer and/or IComparable) you use
interfaces.

You may look upon interfaces as building blocks for your class.
You have your basic class, maybe inherited from another class, and then
you add several interfaces to make it even more useful.

Visual Studio .Net will even fill in the required methods by pressing the
tab key when you add an interface.
 
A good example is sorting objects (in arrays and lists etc). The
documentation just tells you to implement IComparable, which only has a
single method that compares two objects.

So by doing this you can sort objects that are in totally different class
hierarchies - they don't need to have a common ancestor that has a
CompareTo() method, as each can implement its own.

Regards

Ron
 
Ch 8 of Bruce Eckel's "Thinking in C#" may give you
your reason. Sorry, i can't find a link to a d/lable copy.
[and the book has had a rather checkered history].
 
Back
Top