Interfaces in C#

13 Jun

I write code, but mostly single file “scripts.” I am familiar with Object Oriented Programming but rarely implement it – my programs are fairly simple tasks. In an attempt to expand my horizons and build more complex programs, I have attempted to learn some of the concepts of OOP that have confused me.

An interface seems like a simple thing – something that sits between two things and allows one to access the other. The gas pedal of your car is the interface to the cars engine. In programming, I understand an interface to be a contract that defines what a class must do. It can do more, and implement a number of interfaces, but must contain all the methods of each interface. I guess this allows you to replace classes and know that anything you put in will still have certain behaviors (methods). For my purposes, it is a good way to make sure that I define all the functionality I am supposed to – a kind of debugging check on my classes. I can define what a class should do in an interface and my debugger will hold me to it.

Here is a simple interface in C# (I like the idea of naming it a thing and the class a specific type of thing. One example I saw on a Java page named the interface bicycle and the class that implemented it SchwinnBicycle.)

interface Thing
{
void doSomething();
void doSomethingElse();

}

My class implementing the interface:

class SpecificThing : Thing
{
static void Main(string[] args)
{
SpecificThing it = new SpecificThing();
it.doSomething();
it.doSomethingElse();

}
public void doSomething()
{
Console.WriteLine(“I implement the Interface”);
}
public void doSomethingElse()
{
Console.WriteLine(“I implement the Interface too”);
}

}

If I do not implement the interface, I get an error in my debugger and cannot build.

I say it implements the interface but fail to include the methods.

I say it implements the interface but fail to include the methods.

When I add the methods doSomething() and doSomethingElse()

Add the methods and everything runs smoothly.

Add the methods and everything runs smoothly.

An interface defines the behavior of your class. It does NOT define how you must implement that behavior. A function doSomething() can do anything you want it to, but you must include it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: